开发者

Using Where with Lists inside Lists

开发者 https://www.devze.com 2023-01-23 05:29 出处:网络
I need to create a List with Data from a List<List<T>(). I do not need to convert the data; I only need to find Elements with specific information.

I need to create a List with Data from a List<List<T>(). I do not need to convert the data; I only need to find Elements with specific information.

Example: List<Countries>(): in this Li开发者_运维知识库st is another one containing Cities

I need to find the right City (bad example) ^^

I've tried:

countryList.Where(x=>x.Cities.Where(y=>y.Name.Contains("New")));

After searching here, I believe I need something with select.


var cities = from country in countrList
             from city in country.Cities
             where city.Name.Contains("New")
             select city;

or:

var cities = countrList
    .SelectMany(country => country.Cities)
    .Where(city => city.Name.Contains("New"));


Try countriesList.FirstOrDefault( x => x.Cities.Any( y => y.Name.Contains("New"));


I think you want all the cities whose name contains the keyword "New":

var cities = countryList.SelectMany(country => country.Cities)
                        .Where(city => city.Name.Contains("New"))
                        .ToList();


countrList.Where(x=>x.Cities.Any(y=>y.Name.Contains("New")));
0

精彩评论

暂无评论...
验证码 换一张
取 消