根据键排序字典列表 [英] Sorting a list of dictionaries based on a key

查看:101
本文介绍了根据键排序字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含学生数据的字典列表
它类似于

I have a list of dictionaries which contains student data It is something like

List<Dictionary<string, object>> students = new List<Dictionary<string, object>>();
Dictionary<string, object> std1 = new Dictionary<string, object>();
std1["name"] = "sai";
std1["age"] = 22;
std1["gender"] = "male";
students.Add(std1);

Dictionary<string, object> std2 = new Dictionary<string, object>();
std2["name"] = "Julia";
std2["gender"] = "female";
students.Add(std2);

Dictionary<string, object> std3 = new Dictionary<string, object>();
std3 ["name"] = "sunny";
std3 ["age"] = 23;
students.Add(std3);  

我想根据名称/ code>, age gender ,我正在尝试这样的东西:

And I want to sort the list of students based on either name, age or gender, I am trying something like this:

var ordered = students.OrderBy(x => x["name"]);

如果我尝试使用 age gender 它返回错误,该键未找到,因为 std2 没有年龄 std3 没有性别

If I try with either age or gender it is returning an error that key is not found, as std2 doesn't have age and std3 doesn't have gender.

我需要所有的记录,即使它不包含排序键的值,任何方式来解决这个问题,谢谢提前。

I need all the records even it doesn't contain the value for sorted key, Any way to solve this problem, Thanks in advance.

推荐答案

如果您想按所有字典中不存在的键进行排序,则需要返回默认值,例如0。

If you want to sort by a key that is not present in all of the dictionaries, you'll need to return a default value instead, for example 0.

var ordered = students.OrderBy(dict =>
{
    string name;
    if (!dict.TryGetValue("name", out name))
        return "";
    return name;
});

使用条件三元运算符的较短版本:

Shorter version using the conditional ternary operator:

var ordered = students.OrderBy(dict =>
{
    string name;
    return dict.TryGetValue("name", out name) ? name : 0;
});

我使用 Dictionary.TryGetValue(...) ,返回一个bool描述密钥是否在字典中找到,并返回其值。

I use Dictionary.TryGetValue(...) which returns a bool depicting whether the key was found in the dictionary and its value returned.

这篇关于根据键排序字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆