c# 字典 Dictionary排序问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c# 字典 Dictionary排序问题相关的知识,希望对你有一定的参考价值。

现有字典
Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
dic.Add("bca", new List<string>()"xkyz" );
dic.Add("c", new List<string>()"xdz" );
dic.Add("absdc", new List<string>()"xyz" );
dic.Add("dxzcu", new List<string>()"fyz" );
排序依据字典健的长度来排序,越长的越在前面,列表的值不变只改变顺序
Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
dic.Add("dxzcu", new List<string>()"fyz" );
dic.Add("absdc", new List<string>()"xyz" );
dic.Add("bca", new List<string>()"xkyz" );
dic.Add("c", new List<string>()"xdz" );

return dic.OrderByDescending(r => r.Key).ToDictionary(r => r.Key, r => r.Value); 参考技术A 自己继承一个 Dictionary 类,然后在重写排序方法。

按其他字典的结果排序字典

【中文标题】按其他字典的结果排序字典【英文标题】:Order Dictionary by the result of other dictionary 【发布时间】:2022-01-16 13:28:47 【问题描述】:

正在寻找可以帮助我使用 C#、LINQ 的人。

我有一个Dictionary&lt;int,int&gt;,我要这样订购:.OrderBy(_ =&gt; _.Value).ThenBy(_ =&gt; ThisMethodReturnsAnotherIReadOnlyDict&lt;int,int&gt;()).ThenByDescending(_ =&gt; _.Key)

我想要的是按第一个字典的值排序,然后如果仍然有相等的值,我希望ThisMethodReturnsAnotherIReadOnlyDict&lt;int,int&gt;() 打破这条平局。这个ThisMethodReturnsAnotherIReadOnlyDict 的第一个键/值打破平局并处于领先地位。最后,如果一切都失败了,那么按它的键降序排序。

类似的一些数据:

(第一本词典)

[1,400]
[2,550]
[3,200]
[4,200]

(第二本词典)

[3,50]
[4,140]
[2,600]
[1,700]

对于这种情况,我希望我的订单返回:[3,50]

有人可以帮忙吗? 谢谢!

【问题讨论】:

Dictionary&lt;&gt; 的上下文中,“第一个键/值”是什么意思?他们没有秩序…… 这注定要失败。 "出于枚举的目的,字典中的每个项目都被视为一个 KeyValuePair&lt;TKey,TValue&gt; 结构,表示一个值及其键。返回项目的顺序是未定义的。" 来源:MSDN Dictionary<TKey,TValue> Class 【参考方案1】:

看起来你正在寻找这样的东西:

var firstDict = new Dictionary<int, int>() 
    1,400, 
    2,550,
    3,200,
    4,200
;

var secondDict = new Dictionary<int, int>() 
    3,50, 
    4,140,
    2,600,
    1,700
;

var result = (from kvp in firstDict
             join tieBreaker in secondDict on kvp.Key equals tieBreaker.Key
             select new  kvp.Key, V1 = kvp.Value, V2 = tieBreaker.Value )
                .OrderBy(x => x.V1)
                .ThenBy(x => x.V2)
                .ThenByDescending(x => x.Key)
                .First();

这将通过其键将第一个和第二个字典连接在一起,并将分别按第一个字典的值、第二个字典的值然后按键本身降序排列。

【讨论】:

谢谢卡洛斯!我认为这很好用。但是让我们假设第二个字典是空的。那我的加入就不行了。知道如何解决这个问题并只使用第一个吗?再次感谢! @CharlieEcho,您可能想要执行某种左连接。我将编辑答案,以便您更好地使用它。【参考方案2】:

怎么样:

var ans = firstDict
    .OrderBy(kv => kv.Value)
    .ThenBy(kv => ThisMethodReturnsAnotherIReadOnlyDict<int,int>().TryGetValue(kv.Key, out var val2) ? val2 : kv.Key)
    .ToList();

除非ThisMethodReturnsAnotherIReadOnlyDict&lt;int,int&gt; 可能发生变化,否则您可能希望在排序前将返回值缓存在一个变量中。

【讨论】:

以上是关于c# 字典 Dictionary排序问题的主要内容,如果未能解决你的问题,请参考以下文章

C#字典Dictionary排序(顺序倒序)

c#字典dictionary绑定datagridview如何排序

临时解包字典

C#创建安全的字典(Dictionary)存储结构

按其他字典的结果排序字典

Python学习笔记-Dicti和set