Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Because g is a collection of DataRow objects, so

.Select(g => g.First().ToString())

returns a collection of the string System.Data.DataRow

If you want to extract a field from each datarow, then use:

.Select(g => g.First().Field<{type}>("{fieldname}").ToString())

try this

List<string> c_strLSetTitle = Order.AsEnumerable()
                                     .GroupBy(r => r.Field<string>("Job_No"))
                                     .Where(g => g.Count() > 1)
                                    .Select(g => g.Key).ToList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top