2017-04-21 65 views
-1

我需要一些幫助來通過降序嵌套字典進行排序,這對我來說非常困難,因爲我不是很先進,我一直在搜索很多網站,但沒有成功。如果有人能幫我一把,我會很感激。因此,這裏的代碼如何在C#中使用LINQ降序嵌套字典進行排序

Dictionary<string, Dictionary<string, int>> champLeague = new Dictionary<string, Dictionary<string, int>>(); 

例如,當我加 -

巴塞羅那,阿森納,1

人Unted,利物浦,2

曼城,斯托克城,3

我想按照第二個字典的值降序排列字典,如下所示:

var orderedDic = champLeague.OrderByDescending(x => x.Value.Values).ThenBy(x => x.Value.Keys) 

並嘗試foreach(var kvp in orderedDic){Console.WriteLine(kvp.Key)} 這引發了我的異常:「未處理的異常的至少一個對象必須實現IComparable的」

我想是這樣的:

曼城

曼聯

巴塞羅那

+0

字典是用於查找的,但是您可以像使用其他IEnumerable一樣使用它。但你如何試圖擺脫你的數據?你的例子不夠多才多藝。如果相同的值被添加到兩個詞典中,它們應該如何顯示呢?如'巴塞羅那,阿森納,1 曼聯,利物浦,1'你想連續列出這些嗎?還是應該合併所有的字典和它們的價值? –

+0

*例如,當我添加... * - 我們都是程序員在這裏,你可以發佈一些代碼,而不是列出一些不清楚的地方。 –

+0

從你的問題陳述中,我可以理解你想根據目標的數量來排列比賽。對於每個球隊對來說,都會有很多目標。我對嗎? – 2017-04-21 18:13:45

回答

0

您應該嘗試

var allMatches = new List<KeyValuePair<KeyValuePair<string, string>, int>>(); 
foreach(var left in champLeage.Keys) 
{ 
    foreach(var right in left){ 
     allMatches.Add(new KeyValuePair(new KeyValuePair<left, right>(left, right.Key), right.Value); 
    } 
} 

foreach(var match in allMatches.OrderByDescending(x => x.Value)){ 
    ConsoleWriteLine("{0} - {1} : {2}", match.Key.Key, match.Key.Value, match.Value); 
} 

這是不高效或「漂亮」。你應該使用類。一個匹配類有2個團隊和一個結果或類似的東西

0

據我所知,你想按照目標數量降序排列比賽。對於這個特定的問題,我認爲不推薦使用字典。你可以使用元組來代替。當一支球隊有多場比賽時,他們會爲你省去麻煩。 這是代碼。

using System; 
using System.Linq; 
using System.Collections.Generic; 

public class Test 
{ 
    public static void Main() 
    { 
     var tuple1 = 
      new Tuple<string, string, int>("Man City", "Stoke City", 3); 
     var tuple2 = 
      new Tuple<string, string, int>("Man Unted", "Liverpool", 2); 
     var tuple3 = 
      new Tuple<string, string, int>("Barcelona", "Arsenal", 1); 

     var championsLeague = new List<Tuple<string, string, int>>(); 
     championsLeague.Add(tuple1); 
     championsLeague.Add(tuple2); 
     championsLeague.Add(tuple3); 

     //Item3 is the third item from left that mentioned in the definition of the Tuple. ie. Number of goals. 
     var lst = championsLeague.OrderByDescending(x => x.Item3) 
          .Select(x=> x.Item1); // Item1 is the first item mentioned in the tuple definition. 

     lst.ToList().ForEach(Console.WriteLine); 


    } 
} 
+0

「我不知道'Item1'和'Item3'是什麼意思......」每個維護者......都說過。 –