C# 如何使用LINQ在C中使用降序嵌套字典进行排序

C# 如何使用LINQ在C中使用降序嵌套字典进行排序,c#,.net,linq,dictionary,C#,.net,Linq,Dictionary,我需要一些帮助来按嵌套字典的降序排序,这对我来说很难,因为我不是很高级,我已经搜索了很多网站,但都没有成功。如果有人能帮我,我会很感激的。这是代码 Dictionary<string, Dictionary<string, int>> champLeague = new Dictionary<string, Dictionary<string, int>>(); 并在orderedDic{Console.WriteLinekvp.Key}中尝试f

我需要一些帮助来按嵌套字典的降序排序,这对我来说很难,因为我不是很高级,我已经搜索了很多网站,但都没有成功。如果有人能帮我,我会很感激的。这是代码

Dictionary<string, Dictionary<string, int>> champLeague = new Dictionary<string, Dictionary<string, int>>();
并在orderedDic{Console.WriteLinekvp.Key}中尝试foreachvar kvp 它向我抛出一个异常:未处理的异常必须至少实现一个对象为IComparable

我想看起来像这样:

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

曼联

巴塞罗那

你应该试试

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);
}

这既不高效也不美观。你应该使用类。一个包含两支球队和一个结果或类似结果的比赛类

据我所知,您希望按照进球数降序排列比赛。对于这个特殊的问题,我认为不推荐使用字典。您可以改用元组。当一支球队有多场比赛时,他们会帮你省去麻烦。 这是代码

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);


    }
}

字典是用来查找的,但是你可以像其他IEnumerable一样使用它。但你是如何试图把你的数据公布出来的呢?你的例子不够全面。如果两个词典都添加了相同的值,该如何显示它们?e、 巴塞罗那,阿森纳,1人联队,利物浦,1你想把这些列成一行,还是应该合并所有的字典和它们的值?例如,当我加上…-我们都是这里的程序员,你可以发布一些代码,而不是列出一些不清楚的数据。从你的问题陈述中,我可以理解你想根据目标数量来排序匹配。每对球队都会有很多进球。我说的对吗?听起来好像你在使用字典来避免创建一个类,其中包含city、team和rankOk。如果你想看一看的话,这里是带注释的完整代码-我想知道Item1和Item3是什么意思…每个维护人员都这么说…从来没有。