字典列表上的C#Linq对其进行过滤 [英] C# Linq on a list of dictionaries to filter it

查看:805
本文介绍了字典列表上的C#Linq对其进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在不知道如何正确使用LINQ时遇到问题.

I'm having a problem not knowing how to use LINQ properly.

我的ListDictionaries(string, object),如下所示:

[0] -> "field1":1500, "field2":"dog", "field3":"blue"
[1] -> "field1":1700, "field2":"cat", "field3":"brown"
[2] -> "field1":1500, "field2":"horse", "field3":"white"
[3] -> "field1":1900, "field2":"cow", "field3":"black"

我需要从中获取DictionariesList,并且仅将"field1"设置为1500的词典,所以输出应为:

I need to get from this a List of Dictionaries with only the Dictionaries that have the "field1" set to 1500, so the output should be:

[0] -> "field1":1500, "field2":"dog", "field3":"blue"
[1] -> "field1":1500, "field2":"horse", "field3":"white"

我尝试过这样做,但是我确定我距离正确的答案还很遥远.

I tried doing it like this but I'm sure I'm nowhere near the right answer.

List<Dictionary<string, object>> output = input.SelectMany(r => r).Where(r => (r.Key == "field1") && (r.Value == 1500)).ToList();

请为我提供一个解决方案吗?

Please can you suggest me a solution for this?

非常感谢您.

推荐答案

这应该有效:

var result = 
    dicts.Where(
        d => d.TryGetValue("field1", out object value) && value is int i && i == 1500
    ).ToList();

这会选择列表中所有具有名为field1(通过d.TryGetValue())的字段并且该值也是1500的字典.

This picks out all the dictionaries in the list that have a field called field1 (via the d.TryGetValue()) and where that value is also 1500.

请注意,由于字典包含object而不是int,因此您需要使用is int i检查值是否为int.

Note that because the dictionary contains object and not int, you need to check if the value is int using is int i.

还请注意,此语法使用C#版本7或更高版本.

Also note that this syntax uses the C# version 7 or later.

这篇关于字典列表上的C#Linq对其进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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