gpt4 book ai didi

c# - Linq 查询 - 在另一个列表中列出

转载 作者:太空狗 更新时间:2023-10-29 22:18:49 24 4
gpt4 key购买 nike

我正在尝试选择在另一个(提供的)列表中至少有一个城市名称的国家/地区。抱歉难以解释请看下面的代码:

当我调用 GetListOfCountires 时,它应该返回 NZ 和 CN。我也想使用 Linq 而不是 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;
}

谢谢

最佳答案

在您的城市名称列表和每个国家/地区的城市列表之间执行交集,仅返回存在此类交集的国家/地区。

var countries = Countries.Where(x => x.Cities.Intersect(cityNames).Any());

关于c# - Linq 查询 - 在另一个列表中列出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30494807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com