2015-04-07 91 views
0

我有一个胜利百分比的团队字典。我希望能够找到与我发现的球队有相同胜率的球队的字典。 之前,我这样做:Linq查询字典C#

<!-- language: lang-js --> 

foreach (var r in divRanks) 
{ 
    foreach (var rec in divRanks) 
    { 
     if (r.teamID != rec.teamID) 
     { 
      if (r.winPct == rec.winPct) 
      { 
       r.tied = true; 
       rec.tied = true; 
      } 
     } 
    } 
} 

我觉得必须有一个更好的方式让我使用LINQ查询的团队,然后把我绑变量的方式。在包含未绑定的记录之后,我需要这些结果,以便我可以与他们合作。

回答

0

您可以按winPct进行分组,只筛选出只有一个成员的组,并将所有其他项目的tied设置为true

这LINQ查询使用相同divRanks为您的嵌套foreach循环:

var tied = divRanks 
    // Make groups by winning percentage 
    .GroupBy(r => r.winPct) 
    // Throw away all groups of one 
    .Where(g => g.Count() > 1) 
    // Flatten the groups 
    .SelectMany(g => g); 
// Go through the ties, and set the flag 
foreach (var t in tied) { 
    t.tied = true; 
} 
0

你应该结合ToDictionary使用的GroupBy:

var dict = list.GroupBy(item => item.WinPct).ToDictionary(group => group.Key); 
foreach (var item in dict) 
{ 
    Console.Out.WriteLine("Key (winpct which is same for items): {0}", item.Key); 
    if(item.Value.Count() > 1) 
    { 
     foreach (var groupItem in item.Value) 
     { 
      Console.Out.WriteLine("GroupItem: {0} - {1}", groupItem.TeamId, groupItem.WinPct); 
      item.Tied = true; 
     } 
    } 
} 

输入:

list.Add(new Rank() { TeamId = 1, WinPct = 1 }); 
list.Add(new Rank() { TeamId = 2, WinPct = 1 }); 
list.Add(new Rank() { TeamId = 3, WinPct = 2 }); 
list.Add(new Rank() { TeamId = 4, WinPct = 2 }); 
list.Add(new Rank() { TeamId = 5, WinPct = 5 }); 
list.Add(new Rank() { TeamId = 6, WinPct = 6 }); 

输出:

Key (winpct which is same for items): 1 
GroupItem: 1 - 1 
GroupItem: 2 - 1 
Key (winpct which is same for items): 2 
GroupItem: 3 - 2 
GroupItem: 4 - 2 
Key (winpct which is same for items): 5 
GroupItem: 5 - 5 
Key (winpct which is same for items): 6 
GroupItem: 6 - 6 

编辑: 现在它也将设置绑定属性。我以为你只是让这种黑客合并,然后以某种方式后,成为一本字典。如果您只想设置tied属性,则最好使用dasblinkenlights解决方案。

+0

在本例中,我返回了一个基于winPct的字典作为关键字,但是如何知道哪些关键字中有多个关键字? – AmericanSuave

+0

字典项目的值是IGrouping ,它允许您枚举子项目。 (和.Count()也是)。我改变了代码,现在它检查是否有多个相同的条目。 – fixagon