Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq lambda expression to get at least one duplicate along with non duplicates

Tags:

c#

linq

I have a list:

List<Dev> devices= new List<Dev>(){
    new Dev{ Add="5",Name="A" },
    new Dev{ Add="5",Name="a" },
    new Dev{ Add="9",Name="b" },
    new Dev{ Add="6",Name="c" },
    new Dev{ Add="9",Name="b" },

};

I want to write a Linq "Lambda Expression" which return the records that are not duplicates and also the first record from duplicates based on "Name" in the list. Also ignore case while finding duplicates

Expected Output:

Add=5, Name=A
Add=9, Name=b
Add=6, Name=c

Query what I have now (It returns the "Name" which is duplicate):

results.GroupBy(x => x.Name, StringComparer.OrdinalIgnoreCase)
                                  .Where(g => g.Count() > 1)
                                  .Select(g => g.Key)
                                  .ToList();    
like image 765
Dot Net Dev Avatar asked Dec 03 '25 20:12

Dot Net Dev


1 Answers

You are pretty close: rather than picking g.Key, pick g.First(), and remove filtering by count:

var list = results.GroupBy(x => x.Name, StringComparer.OrdinalIgnoreCase)
                  .Select(g => g.First())
                  .ToList();
like image 135
Sergey Kalinichenko Avatar answered Dec 05 '25 10:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!