简体   繁体   English

如何订购清单结果 <IDictionary> 对象使用Linq?

[英]How do I order results of a List<IDictionary> object using Linq?

Hi and thanks for looking! 您好,感谢您的光临!

Background 背景

I have a workflow that constructs a set of dictionaries, each with identical KEYS, but (of course) various VALUES. 我有一个工作流,它构造了一组字典,每个字典都具有相同的KEYS,但是(当然)具有各种VALUES。 After these dictionaries are constructed, they are added to a common list. 这些字典构建之后,将它们添加到公用列表中。 I need to order that list based on a particular KEY in each dictionary. 我需要根据每个字典中的特定KEY来排序该列表。

I am using C#, .NET 4, LINQ, Lambdas, etc. 我正在使用C#、. NET 4,LINQ,Lambdas等。

Question

How do I order a list of dictionaries based on a common key property in each dictionary? 如何根据每个词典中的公共键属性对词典列表进行排序? For example if I have the code below, how do I order based on the "Color" key? 例如,如果我有下面的代码,如何根据“颜色”键订购?

IDictionary<String, object> item1 = new Dictionary<String, object>{"Color","Red"};
IDictionary<String, object> item2 = new Dictionary<String, object>{"Color","Blue"};
IDictionary<String, object> item3 = new Dictionary<String, object>{"Color","Green"};

var dictionaryList = new List<IDictionary<String, object>>();

dictionaryList.add(item1);
dictionaryList.add(item2);
dictionaryList.add(item3);

var orderedList = dictionaryList.OrderBy[??????];

Thanks! 谢谢!

除非我想念什么?

var orderedList = dictionaryList.OrderBy(d => d["Color"]);

You need to pass the OrderBy method a function that given a Dictionary<String, object> returns the item you wish to order by, so: 您需要传递给OrderBy方法一个给定Dictionary<String, object>返回想要排序的商品的函数,因此:

var orderedList = dictionaryList.OrderBy(d => d["Color"]);

Will suffice. 就足够了。

As an aside, you can clean up the initialisation a little bit like so: 顺便说一句,您可以像这样清理初始化:

var orderedList = new[] { item1, item2, item3 }.OrderBy(d => d["Color"]);

您正在寻找d => d["Color"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM