Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flag all but one duplicates in a list

I have the list of objects of the following class,

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

The invoice numbers can be duplicate or there can even be a case of 4 invoices , all with the same number.

I need to set the IsDupe flag on all except one of the invoice object. One approach is the brute force method of having a list of invoice numbers and comparing each one to flag. I have also tried this question . Is there any better syntactical way to do it ? TIA

like image 999
SJMan Avatar asked Dec 11 '15 04:12

SJMan


1 Answers

This 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);

Produces

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

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

like image 136
Rob Avatar answered Oct 13 '22 00:10

Rob