2013-04-01 84 views
1

我有一個List<Car> lstcar與性能得到重複的字段名稱的單一列表

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 

我想基於名稱 如重複項目的名稱:我希望「禪,納米」,但是當我做

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

添加Where條款只得到更多的則1元和SelectMany組拼合結果到一個列表:

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

我看你會不會和同組,所以你應該改變你的GroupBy爲:GroupBy(s => s.CarName.ToLower())

+0

非常感謝!工作:) – user1799214