字典列表上的C#Linq对其进行过滤 [英] C# Linq on a list of dictionaries to filter it
问题描述
我在不知道如何正确使用LINQ时遇到问题.
I'm having a problem not knowing how to use LINQ properly.
我的List
为Dictionaries(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"
我需要从中获取Dictionaries
的List
,并且仅将"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屋!