如何在C#(使用.NET 3.5)中使用Linq对有序字典进行排序?
我需要对OrderedDictionary(System.Collections.Specialized)进行排序 我有以下代码:如何在C#(使用.NET 3.5)中使用Linq对有序字典进行排序?,c#,.net,linq,C#,.net,Linq,我需要对OrderedDictionary(System.Collections.Specialized)进行排序 我有以下代码: var od = new System.Collections.Specialized.OrderedDictionary(); od.Add("a1", 3); od.Add("a2", 5); od.Add("a3", 2); od.Add("a4", 4); 我希望使用值对其进行排序。我可以使用Linq吗?您可以轻松地按值枚举值/条目。为了激活linq功能,
var od = new System.Collections.Specialized.OrderedDictionary();
od.Add("a1", 3);
od.Add("a2", 5);
od.Add("a3", 2);
od.Add("a4", 4);
我希望使用值对其进行排序。我可以使用Linq吗?您可以轻松地按值枚举值/条目。为了激活linq功能,您只需将其转换为适当的类型
var sortedOrder = od.Values
.Cast<int>() // this is an enumeration of ints
.OrderBy(i => i);; // enumerate through ordered by the value
foreach (var item in sortedOrder)
{
// do stuff
}
var sortedOrder=od.值
.Cast()//这是整数的枚举
.OrderBy(i=>i);//按值的顺序枚举
foreach(分拣机中的var项目)
{
//做事
}
以下内容将根据您的OrderedDictionary为您提供一个已排序词典
var normalOrderedDictionary= od.Cast<DictionaryEntry>()
.OrderBy(r=> r.Value)
.ToDictionary(c=> c.Key, d=> d.Value);
(确保用正确的键和值类型替换上一行中的字符串
)
输出:
foreach (var entry in sortedDictionary)
Console.WriteLine("Key: {0} Value: {1}", entry.Key, entry.Value);
Key: a3 Value: 2
Key: a1 Value: 3
Key: a4 Value: 4
Key: a2 Value: 5
太好了,这会有帮助的。还有AsQueryable()方法的作用。我可以使用linq查询进行排序。
AsQueryable()
只是将集合强制转换为IQueryable
(与IEnumerable
相反)。IQueryables在创建查询时接受lambda表达式,从而更容易创建动态查询。谢谢Habib。您的答案也很有效。我只是没有太多的声望点。它有石头我昨天试图想出这个办法,但一开始没有成功。现在看看这个示例,一切都像晴朗的天空一样清晰…是否将ToDictionary()
制作一个通用(非有序)词典?是的-这个答案是错误的ToDictionary()
返回一个常规的词典
,其中顺序不受保证。@NetMage,你是对的,ToDictionary
将返回一个常规词典,尽管它的顺序保证会被维护以进行查找(因为在创建时OrderBy),但一旦添加了新项,订单不能保证。我修改了答案以反映这一点。再次感谢。
foreach (var entry in sortedDictionary)
Console.WriteLine("Key: {0} Value: {1}", entry.Key, entry.Value);
Key: a3 Value: 2
Key: a1 Value: 3
Key: a4 Value: 4
Key: a2 Value: 5