Mark only one duplicate in the list

I have a list of objects of the following class,

class Invoice { public int InvoiceNumber; public string CustomerName; public bool IsDupe; } 

The invoice numbers can be duplicated, or maybe even the case with 4 invoices, all with the same number.

I need to set the IsDupe flag on all but one account object. One approach is brute force, which has a list of account numbers and a comparison of each for the flag. I also tried this question . Is there a better syntax way to do this? TIA

+7
collections list c # duplicates
source share
2 answers

Assuming you have a list of these items, you can use LINQ and use the ForEach extension:

 List<Invoice> invoices = /* */; invoices .GroupBy(inv => inv.InvoiceNumber) .ForEach(group => group.Skip(1).ForEach(notFirst => notFirst.IsDupe = true)); 

It groups accounts up by InvoiceNumber , and if the group contains more than one element, then it sets IsDupe to true for all but the first.

However, using ForEach seems non-LINQ-compatible and less readable to me.
It looks great using ForEach :

 foreach (var group in invoices.GroupBy(inv => inv.InvoiceNumber)) { foreach (var notFirstItem in group.Skip(1)) { notFirstItem.IsDupe = true; } } 

Now it is absolutely readable - take each group, take all the elements except the first, and mark IsDupe = true .

+4
source share

It works.

 var invs = new List<Invoice> { new Invoice { InvoiceNumber = 1 }, new Invoice { InvoiceNumber = 1 }, new Invoice { InvoiceNumber = 1 }, new Invoice { InvoiceNumber = 2 }, new Invoice { InvoiceNumber = 3 }, new Invoice { InvoiceNumber = 3 } }; invs.ForEach(i => i.IsDupe = true); invs.GroupBy (i => i.InvoiceNumber) .Select(g => g.First()) .ToList() .ForEach(i => i.IsDupe = false); 

Gives out

 1 null False 1 null True 1 null True 2 null False 3 null False 3 null True 

Alternatively, you can call the IsNotDupe property and take advantage of the fact that the boolean defaults to false (you can remove the first ForEach )

+5
source share