user2140261 user2140261 - 2 months ago 8
C# Question

Why does Linq ToList<string> return System.Data.DataRow?

When using the below code it works fine to return a var that is filled with DataRows I can loop:

var GetSetRows = Order.AsEnumerable()
.GroupBy(r => r.Field<string>("Job_No"))
.Where(g => g.Count() > 1)
.Select(g => g.First());


but what I would like to do is return a
List<string>
instead.

I tried:

List<string> c_strLSetTitle = Order.AsEnumerable()
.GroupBy(r => r.Field<string>("Job_No"))
.Where(g => g.Count() > 1)
.Select(g => g.First().ToString()).ToList();


but this returns a list filled with elements that say
System.Data.DataRow
, but it does return the correct amount, i.e. that amount of items that I am expecting to be returned.

Answer

g.First() returns object of type DataRow. Then you are calling ToString() which returns the type name System.Data.DataRow. At the end you have a list of type names.

If you want to select a particular column, then project group of rows into value of some field of (first) row:

g.First().Field<string>("FieldName")

Or you can use grouping key if you want to return values of Job_No filed:

List<string> c_strLSetTitle = Order.AsEnumerable()
                                   .GroupBy(r => r.Field<string>("Job_No"))
                                   .Where(g => g.Count() > 1)
                                   .Select(g => g.Key).ToList();

That will return values of duplicated Job_No fields.