简体   繁体   中英

Linq Where not filtering values

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();

I expected to get the result:

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() 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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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