Home > DeveloperSection > Forums > Get Duplicate field Name in single list
Goti Bandu

Total Post:119

Points:835
Posted on    August-29-2014 12:59 AM

 C#
Ratings:


 1 Reply(s)
 703  View(s)
Rate this:

I have a List<Car> lstcar with properties

name-Zen id-1211 MfYear-1990 Color-black

name-Alto id-1521 MfYear-1990 Color-black

name-Nano id-9911 MfYear-1990 Color-black

name-800 id-1721 MfYear-1990 Color-black

name-zen id-711 MfYear-1990 Color-black

name-Swift id-9911 MfYear-1990 Color-black

name-Nano id-1081 MfYear-1990 Color-black

I want name of repeated items based on name eg: I want "Zen , Nano", but when I do

   List<Car> dup = lstcar.GroupBy(s => s.CarName)

         .Select(grp => grp.FirstOrDefault())

         .OrderBy(s => s.CarName)

         .ToList<Car>();

I get dup has this value

name-Zen id-1211 MfYear-1990 Color-black

name-Alto id-1521 MfYear-1990 Color-black

name-Nano id-9911 MfYear-1990 Color-black

name-800 id-1721 MfYear-1990 Color-black    

name-Swift id-9911 MfYear-1990 Color-black

but I want

 name-Zen id-1211 MfYear-1990 Color-black    

 name-Nano id-9911 MfYear-1990 Color-black   

 name-zen id-711 MfYear-1990 Color-black  

 name-Nano id-1081 MfYear-1990 Color-black

How do I get duplicates from one List<T> ?



Sumit Kesarwani

Total Post:378

Points:2694
Posted on    September-01-2014 12:14 AM

Add Where clause to get only groups with more then 1 element and SelectMany to flatten results into one list:

var duplications = lstcar.GroupBy(s => s.CarName)

                         .Where(g => g.Count() > 1)

                         .SelectMany(g => g)

                         .ToList();

I see you won't Zen and zen in the same group, so you should change your GroupBy to: GroupBy(s => s.CarName.ToLower())


Don't want to miss updates? Please click the below button!

Follow MindStick