Tôi đang cố gắng chọn các quốc gia có ít nhất một tên thành phố trong danh sách khác (được cung cấp). Rất tiếc khi được giải thích, vui lòng xem mã bên dưới:Truy vấn LINQ - Danh sách trong danh sách khác
Khi tôi gọi GetListOfCountires, nó sẽ trả về NZ và CN. Ngoài ra tôi muốn sử dụng LINQ thay vì 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;
}
Cảm ơn