2017-05-10 20 views
1

我有看起来像这样的例子列表:C#组列表,并把统计到列表变量

Id = 1, Name = Microsoft, Country = USA, Match = null 
Id = 2, Name = Google, Country = USA, Match = null 
Id = 1, Name = Microsoft, Country = USA, Match = null 

现在我想通过我不喜欢这个名字组名单:

var List = result.GroupBy(x => x.Name).ToList(); 

我的目标是将重复的数量安全地转换为Match。 因此,列表看起来像这样:

Id = 1, Name = Microsoft, Country = USA, Match = 2 
Id = 2, Name = Google, Country = USA, Match = 1 

在此先感谢!

回答

7

我会根据所有三个属性进行分组,因此它们将对组中的所有项目具有相同的值。这将简化构建聚合实体:

var List = result.GroupBy(x => new { x.Name, x.Id, x.Country }) 
      .Select(g => new YourType { 
       Id = g.Key.Id, 
       Name = g.Key.Name, 
       Country = g.Key.Country, 
       Match = g.Count() 
      }) 
      .ToList(); 

如果微软在其他国家(不仅是美国)和你想重复的只是公司名称数量(无论是位于美国或没有),那么您应该从密钥和聚合实体中删除Country

+1

谢谢,这样做! – Anokrize

+0

如果我只想按姓名分组,但不想按国家分组,但仍然想将国家列入名单中,我该怎么做? – Anokrize

+1

@Anokrize那么你应该定义你想包含哪个国家。因为会有几个实体名称相同,但国家不同 –