2015-04-07 89 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