2017-04-21 77 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'是什么意思......”每个维护者......都说过。 –