I'm using linq on a DataTable (in c#), and was wondering how to group by multiple fields. I discovered that it can be done with an anonymous class, e.g.
var a = dt.AsEnumerable().GroupBy(e => new { name = e["Name"] })
problem is, my grouping key is dynamically determined at runtime. so I instead tried grouping by a Dictionary instead:
var a = dt.AsEnumerable().GroupBy(e => GetKey(e))
where GetKey(e)
returns a Dictionary<string, object>
. the idea is that the dictionary values sort of take the place of the anonymous class keys and values. my problem is that the linq query no longer works as desired - it doesn't seem to do any grouping at all. my hunch is that it's because internally it has to compare the grouping key for each DataTable row, and the dictionary keys aren't considered equal just because they have the same keys and values, so each row has a different grouping key and are thus not aggregated.
if I'm right on that, what's the proper way to address this? I tried wrapping the dictionary in a class, and overriding the Equals() method, but it was never called.