Linq查询-在另一个列表中列出 [英] Linq query - List within another list
本文介绍了Linq查询-在另一个列表中列出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在另一个(提供的)列表中选择城市名称至少一个的国家.不好意思,请看下面的代码:
I am trying to select countries with at least one of their cities' name in another (supplied) list. Sorry hard to explain please see code below:
当我调用GetListOfCountires时,它应该返回NZ和CN.我也想用Linq代替foreach.
When i call GetListOfCountires, it should return NZ and CN. Also I want to use Linq instead of foreach.
private static List<Country> Countries = new List<Country>();
private static void Main()
{
var city1 = new City {Name = "Auckland"};
var city2 = new City { Name = "Wellington" };
var city3 = new City { Name = "Perth" };
var city4 = new City { Name = "Sydney" };
var city5 = new City { Name = "Beijing" };
var country1 = new Country {Name = "NZ", Cities = new List<City> {city1, city2}};
var country2 = new Country { Name = "AU", Cities = new List<City> { city3, city4 } };
var country3 = new Country { Name = "CN", Cities = new List<City> { city5 } };
Countries.Add(country1);
Countries.Add(country2);
Countries.Add(country3);
List<String> cityNames = new List<string>{"Auckland", "Beijing"};
var countries = GetListOfCountires(cityNames); // this should return NZ, and CN
}
public class Country
{
public string Name;
public List<City> Cities = new List<City>();
}
public class City
{
public string Name;
}
public static List<Country> GetListOfCountires(List<String> cityNames)
{
List<Country> result = new List<Country>();
foreach (var cityName in cityNames)
{
result.Add(Countries.Where(x=>x.Cities.Contains(cityName))); // error???
}
return result;
}
谢谢
推荐答案
在您的城市名称列表和每个国家/地区的城市列表之间进行交集,仅返回存在这种交集的国家/地区.
Perform an intersection between your list of city names and each country's list of cities, returning only those countries where such an intersection exists.
var countries = Countries.Where(x => x.Cities.Intersect(cityNames).Any());
这篇关于Linq查询-在另一个列表中列出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文