1

我有一个List<Car> lstcarwith 属性

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

我想要基于名称的重复项目的名称,例如:我想要“Zen,Nano”,但是当我这样做时

   List<Car> dup = lstcar.GroupBy(s => s.CarName)
         .Select(grp => grp.FirstOrDefault())
         .OrderBy(s => s.CarName)
         .ToList<Car>();

我得到dup了这个值

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

但我想要

 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

如何从一个中获取重复项List<T>

4

1 回答 1

4

添加Where子句以仅获取具有 1 个以上元素的组并将SelectMany结果展平到一个列表中:

var duplications = lstcar.GroupBy(s => s.CarName)
                         .Where(g => g.Count() > 1)
                         .SelectMany(g => g)
                         .ToList();

我看到你不会Zenzen在同一组中,所以你应该改变你GroupBy的:GroupBy(s => s.CarName.ToLower())

于 2013-04-01T18:31:43.620 回答