I am trying to get one row per id
from a DataTable, and I do not care which row I take. The same id
can exist on several rows in the table.
Here's the expression that's giving me trouble:
dt.AsEnumerable().GroupBy(i => i.Field<int>("id")).Select(i => i.First())
Running just this section dt.AsEnumerable().GroupBy(i => i.Field<int>("id")
correctly gives me a result of 22 groupings for my DataTable. (I have 22 ids with data in this table)
However, when adding on the .Select(i => i.First())
, I am only seeing 10 data rows.
To me this doesn't seem to make any sense. If the GroupBy
function managed to find 22 distinct id
values, I would expect this logic to grab one of each.
My only other thought is that maybe it's just a weird side effect of viewing this data through a watch in Visual Studio rather than assigning to a variable.
CodePudding user response:
If you think it's just weird side effects of viewing the data in a watch, which can happen with LINQ statements, then split it out into
var groups = dt.AsEnumerable().GroupBy(i => i.Field<int>("id")).ToList();
var firstOfGroups = groups.Select(i => i.First()).ToList();
and then look at groups
and firstOfGroups
in the debugger. Temporarily evaluating items with .ToList()
can help a lot with viewing things in the debugger.
CodePudding user response:
I think it is possible, can double check the count of each group items
.Select(g=>new { k = g.Key, c = g.Count() })