嵌套为Linq,带有链接链接列表[英] nested foreach as LINQ with chained linked List

本文是小编为大家收集整理的关于嵌套为Linq,带有链接链接列表的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我在列表中有一个列表.我只需要列表中的一个值,并且可以使用嵌套的foreach获得我的结果,但我想使用某种linq查询.

我的代码:

var myCity = from c in CountryLists
           select (from city in c.stateList
                   where city.name == passedInValue
                   select city.name).FirstorDefault();

这将Mycity作为某种列表返回,所有值的列表为null 在找到比赛的位置.

我不想浏览城市清单才能找到名称.我如何只有一个价值的置身价值? null或所需的名称?

推荐答案

首先,使用SelectMany将列表弄平,然后FirstOrDefault过滤:

CountryList.SelectMany(c => c.stateList).FirstOrDefault(d => d.Name == passedInValue);

请注意,由于FirstOrDefault可以采用谓词,因此您实际上不需要Where子句.

其他推荐答案

使用SelectMany:

var city = CountryLists
           .SelectMany(x => x.stateList)
           .FirstOrDefault(x => x.name == passedInValue);

其他推荐答案

您可以按照其他指出的方式使用SelectMany(我更喜欢该解决方案),但是,如果您需要查询语法,则可以使用多个from条款(检查 msdn文档 有关更多示例):

var city = (from c in CountryLists
            from city in c.stateList
            where city.name == passedInValue
            select city.name).FirstOrDefault();

它等效于SelectMany方法解决方案,无论如何它在封面下使用它.

本文地址:https://www.itbaoku.cn/post/1556817.html

问题描述

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.

my code:

var myCity = from c in CountryLists
           select (from city in c.stateList
                   where city.name == passedInValue
                   select city.name).FirstorDefault();

This returns myCity as a list of some sort with all values as null EXCEPT for where the match was found.

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?

推荐答案

First, use SelectMany to flatten the list, then FirstOrDefault to filter:

CountryList.SelectMany(c => c.stateList).FirstOrDefault(d => d.Name == passedInValue);

Note that because FirstOrDefault can take a predicate, you don't actually need the Where clause.

其他推荐答案

How about using SelectMany:

var city = CountryLists
           .SelectMany(x => x.stateList)
           .FirstOrDefault(x => x.name == passedInValue);

其他推荐答案

You can use SelectMany as other have pointed out (and I prefer that solution myself), however if you'd like the query syntax, you can use multiple from clauses (check the MSDN documentation for more examples):

var city = (from c in CountryLists
            from city in c.stateList
            where city.name == passedInValue
            select city.name).FirstOrDefault();

It is equivalent to the SelectMany method solution, it uses it under the covers anyway.