Linq哪里不过滤值 [英] Linq Where not filtering values

查看:35
本文介绍了Linq哪里不过滤值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使用一个简单的LINQ where子句.这是我的示例:

I am struggling with a supposedly easy LINQ where clause. Here my example:

Dictionary<string,string> test= new Dictionary<string,string>();

test.Add("12342","F650");
test.Add("12341","F000");
test.Add("12340","F650");
test.Add("12343","0E0E");

var result=test;

string searchCriteria = "F000,0E0E";

foreach (string tsearchCritera in searchCriteria.Split(','))
{
    string temp = tsearchCritera;
    result.Where(a=>a.Value.Equals(temp));
}

result.Select(a=>a.Key).Dump();

我希望得到结果:

12341 and 12343

相反,它返回字典的所有条目.

Instead it returns all entries of the Dictionary.

有什么主意如何解决这个问题,以便只获取两个匹配的条目?

Any idea how to solve this to get only the two matching entries?

推荐答案

.Where()不能用作就地集合过滤器;它仅对集合应用过滤器,以期望您随后在枚举集合时解决下游查询(例如,使用 .Select() .ToList()),则在查询的解析范围内应用过滤器 .

.Where() does not act as an in-place, in-collection filter; it only applies a filter to the collection with the expectation that you then resolve the query downstream when you enumerate the collection (such as with .Select() or .ToList()), applying the filter during the resolution of the query.

您需要返回 .Where()的结果,并使用该新结果来选择匹配的键.

You need to return the result of .Where() and use that new result to select the matched keys.

Dictionary<string, string> test = new Dictionary<string, string>();

test.Add("12342", "F650");
test.Add("12341", "F000");
test.Add("12340", "F650");
test.Add("12343", "0E0E");

var result = test;
var filteredResults = new List<KeyValuePair<string, string>>();

string searchCriteria = "F000,0E0E";

foreach (string tsearchCritera in searchCriteria.Split(','))
{
    string temp = tsearchCritera;
    filteredResults.AddRange(result.Where(a => a.Value.Equals(temp)));
}

filteredResults.Select(a => a.Key).Dump();

这篇关于Linq哪里不过滤值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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