c# - How do we find duplicates in a list of objects -
this question has answer here:
- c# linq find duplicates in list 5 answers
how find duplicates in list of objects based on multiple properties?
the following code not returning if list contains dupes or not.
var dups = listitems.groupby(i => new { i.value, i.code }) .where(g => g.count() >= 1) .select(g => new { length = g.key.value, label = g.key.code, count = g.count() });
i guess have error in condition where(g => g.count() >= 1) return groups 1 or more items (actually group have @ least 1 item condition true).
if want duplicates should be: where(g => g.count() > 1).
so result code be:
var dups = listitems.groupby(i => new { i.value, i.code }) .where(g => g.count() > 1) .select(g => new { length = g.key.value, label = g.key.code, count = g.count() }); in way in dups have groups of more 1 items duplicated value , code.
also think better if call select before where because calculating count of items in group twice, inside where check condition , inside select store count.
if call where after 'select' able filter using stored value of group count, this:
var dups = listitems.groupby(i => new { i.value, i.code }) .select(g => new { length = g.key.value, label = g.key.code, count = g.count() }) .where(g => g.count > 1);
Comments
Post a Comment