Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query - List within another list

Tags:

c#

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:

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;
    }

Thanks

like image 533
meenakshi Avatar asked May 27 '15 23:05

meenakshi


2 Answers

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());
like image 59
Grant Winney Avatar answered Nov 04 '22 10:11

Grant Winney


What you need to do get the countries where Any of their cities is in the cityNames list

public static List<Country> GetListOfCountires(List<String> cityNames)
{
    return Countries
           .Where(country => country.Cities.Any(city => cityNames.Contains(city.Name))
           .ToList()

}
like image 5
Luiso Avatar answered Nov 04 '22 10:11

Luiso