简体   繁体   English

c#订购一个List <Dictionary<string,object> &gt;

[英]c# order a List<Dictionary<string,object>>

how to order a List<Dictionary<String,object>> the object contains only string 如何订购List<Dictionary<String,object>>该对象只包含字符串

the dictionary is structured as below 字典的结构如下

[name: mario]
[surname: rossi]
[address: xxxxxx]
[age: 40]

i'd like to order the list of these dictionaries by "age" may you help me please? 我想按“年龄”订购这些词典的名单你可以帮我吗?

i've tried with: 我尝试过:

myList.Select(x => x.OrderBy(y=>y.Value)) 

it gives me this error: the value isn't a string(ok i aggree with him, it's an object, i've to cast in some way) but more important is that i can't tell to the "orderby" methods that it must order by age 它给了我这个错误:值不是一个字符串(好吧我和他一起对,它是一个对象,我要以某种方式进行投射)但更重要的是我无法告诉“orderby”方法它必须按年龄排序

You want something along the lines of 你想要一些东西

var sorted = myList.OrderBy(dict => Convert.ToInt32(dict["age"]));

I 've used Convert.ToInt32 defensively because there's a small chance you are using another data type for the age, and casting (unboxing) to the wrong type would throw an exception. 我在防御上使用了Convert.ToInt32因为你使用另一种数据类型的可能性很小,而将(拆箱)转换为错误类型会引发异常。

myList.Sort((x,y) => ((int)x["age"]).CompareTo((int)y["age"]));

or similar: 或类似的:

myList.Sort((x, y) => Comparer.Default.Compare(x["age"], y["age"]));

However! 然而! It would be much easier if you used a proper type instead of the dictionary; 如果你使用正确的类型而不是字典会更容易; then it would just be: 然后它只会是:

myList.Sort((x,y) => x.Age.CompareTo(y.Age));

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

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