我正在努力选择至少拥有其中一个城市的国家/地区。另一个(提供)列表中的名称。很抱歉很难解释,请参阅下面的代码:
当我调用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;
}
谢谢
答案 0 :(得分:7)
在您的城市名称列表和每个国家/地区的城市列表之间执行交集,只返回存在此类交叉点的国家/地区。
var countries = Countries.Where(x => x.Cities.Intersect(cityNames).Any());
答案 1 :(得分:5)
您需要做什么才能让Any
列表中cityNames
列出的public static List<Country> GetListOfCountires(List<String> cityNames)
{
return Countries
.Where(country => country.Cities.Any(city => cityNames.Contains(city.Name))
.ToList()
}
个国家/地区
services.factory('errorInterceptor', ['$injector','$location', function ($injector, $location, $q, $state) {
return {
'responseError': function (rejection) {
$injector.get('$state').transitionTo('404');
return $q.reject(rejection);
}
};
}]);
services.config(function ($httpProvider) {
$httpProvider.interceptors.push('errorInterceptor');
});