i got a code for converting datatable to ilist. which may work but the code not very clear to me. here is code
table.AsEnumerable()
.Select(r => table.Columns.ToDictionary(c => c.ColumnName, c => r[c]))
.ToList();
what is table.Columns.ToDictionary()…what it does. what is the meaning of c => c.ColumnName, c => r[c]
what r[c] return. not very clear to me.
i got a another snippet….here it is
var list = new List<DataRow>();
foreach (var row in table.Rows)
list.Add(row);
return list;
this code is clear to me but i want to know which code has good performance out of 2 different snippet. please discuss. thanks
The
ToDictionarycall converts eachDataRowto aDictionary<string, object>which you can use to find the value of any field within the row.=>is the syntax used in a lambda expression – you should really learn about lambda expressions if you’re going to do any significant amount of work with LINQ.Your second snippet would be more simply written as:
In terms of efficiency – the first form fetches all the data from the row as it builds the dictionary. That’s likely to make it less efficient if you only need to look at some of the fields. On the other hand, it may be more convenient. It depends on what you do with it later. In terms of memory, the second form will mean the
DataRowobjects themselves can’t be garbage collected, whereas the first form doesn’t need the rows afterwards – but it’s created a copy of all the actual data. Whether that’s relevant in your situation will again depend on the rest of your code.I wouldn’t focus on the performance to start with though – start off with whichever code makes the rest of your application simplest to write, then check whether that performs well enough.