Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use LINQ to find the duplicate of a specific property?

Tags:

c#

linq

Customer customerOne = new Customer("John", "Doe"); Customer customerTwo = new Customer("Super", "Man"); Customer customerThree = new Customer("Crazy", "Guy"); Customer customerFour = new Customer("Jane", "Doe"); Customer customerFive = new Customer("Bat", "Man");  List<Customer> customers = new List<Customer>(); customers.Add(customerOne); customers.Add(customerTwo); customers.Add(customerThree); customers.Add(customerFour); customers.Add(customerFive); 

What LINQ query would return an enumerable for all customers with the same last name?

Results should include one instance of: John Doe, Jane Doe, Super Man, and Bat Man

like image 369
mbursill Avatar asked Nov 22 '10 21:11

mbursill


People also ask

How do I find duplicate records in LINQ?

To find the duplicate values only:var duplicates = list. GroupBy(x => x. Key). Where(g => g.


2 Answers

 customers.GroupBy(c => c.LastName).Where(g => g.Skip(1).Any()).SelectMany(c => c) 

or with LINQ syntax:

        var q = from c in customers                 group c by c.LastName into g                 where g.Skip(1).Any()                 from c in g                 select c; 
like image 173
jeroenh Avatar answered Oct 10 '22 03:10

jeroenh


    var result = from c in customers                  join c2 in customers on c.LastName equals c2.LastName                  where c != c2                  select c; 
like image 29
Mikael Eliasson Avatar answered Oct 10 '22 02:10

Mikael Eliasson