Get Duplicate field Name in single list

Total Post:119

Points:835
C#
 1199  View(s)
Ratings:
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> ?

  1. Post:378

    Points:2694
    Re: Get Duplicate field Name in single list

    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())

      Modified On Apr-05-2018 04:55:13 AM

Answer