作为LINQ嵌套的foreach,带有链接的链表 [英] nested foreach as LINQ with chained linked List
问题描述
我在列表中有一个列表.我只需要列表中的一个值,就可以使用嵌套的foreach获得结果,但是我想使用某种LINQ查询.
I have a List within a list. I only need the one value from the list and can do obtain my result with a nested foreach but I want to use a LINQ query of some sort.
我的代码:
var myCity = from c in CountryLists
select (from city in c.stateList
where city.name == passedInValue
select city.name).FirstorDefault();
这会返回myCity作为某种形式的列表,其中所有值都为null EXCEPT (找到匹配项的位置).
This returns myCity as a list of some sort with all values as null EXCEPT for where the match was found.
我不想遍历城市列表来查找名称.我如何在myCity中仅拥有一个价值;是null还是所需的名称?
i don't want to have to walk through the city list to find the name. How can I have only one value in myCity; either null or the desired name?
推荐答案
首先,使用SelectMany
展平列表,然后使用FirstOrDefault
进行过滤:
First, use SelectMany
to flatten the list, then FirstOrDefault
to filter:
CountryList.SelectMany(c => c.stateList).FirstOrDefault(d => d.Name == passedInValue);
请注意,由于FirstOrDefault
可以使用谓词,因此实际上不需要Where
子句.
Note that because FirstOrDefault
can take a predicate, you don't actually need the Where
clause.
这篇关于作为LINQ嵌套的foreach,带有链接的链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!