c# - remove duplicates from each group after .GroupBy() -
var groupedlist = mylist.groupby(mytype => mytype.category).tolist()
groupedlist
ienumerable<igrouping<category, mytype>>
now distinct() on specific property of mytype each igrouping<category, mytype>
remove duplicates. return value needs same type groupedlist
.
so here solution. it's not ideal in terms of performance, in groupby
@ end bit redundant, proper types it's not super expensive operation, should enough.
groupedlist = groupedlist.selectmany(group => group.distinctby(mytype => mytype.someproperty) .select(item => new { key = group.key, element = item, })) .groupby(pair => pair.key, pair => pair.element) .tolist();
if create group
class, so:
public class group<tkey, telement> : igrouping<tkey, telement> { private ienumerable<telement> elements; public group(tkey key, ienumerable<telement> elements) { this.elements = elements; key = key; } public tkey key { get; private set; } public ienumerator<telement> getenumerator() { return elements.getenumerator(); } ienumerator ienumerable.getenumerator() { return getenumerator(); } } public static group<tkey, telement> creategroup<tkey, telement>( tkey key, ienumerable<telement> elements) { return new group<tkey, telement>(key, elements); }
then can do:
groupedlist = groupedlist.select(group => (igrouping<string, foo>)creategroup(group.key, group.distinctby(mytype => mytype.someproperty))) .tolist();
Comments
Post a Comment