Home > Software engineering >  Is GroupBy based on another list possible in C#?
Is GroupBy based on another list possible in C#?

Time:12-17

Assuming that I had code like this, where each country had a list of all city IDs that belong to this country, but city objects had no information about which country they belong to, would it be possible to group cities by country?

public class Country
{
  public int Id { get; set; }
  public List<int> CityIds { get; set; }
}

public class City
{
  public int Id { get; set; }
}

List<City> cities = _database.GetAllCities();
List<Country> countries = _database.GetAllCountries();

var citiesGroupedByCountry = cities.GroupBy(.... ?);

CodePudding user response:

You can use anonymous an create the link inversely.

// get all your citites and country
List<City> cities = _database.GetAllCities();
List<Country> countries = _database.GetAllCountries();

// country are already grouped so you just need the select
var CitiesByCountry = countries.Select(country => new { Country = country, Citites = CityIds.Select(cid => cities.FirstOrDefault(c => c.Id == cid)).ToList()).ToList();

// read the values
var firstcountry = CitiesByCountry[0].Country;
var firstcountryCities = CitiesByCountry[0].Cities;

CodePudding user response:

You can use a simple where clause since you already have CityIds grouped by Country in the Country object

pseudo code:

public class Country
{
  public int Id { get; set; }
  public List<int> CityIds { get; set; }
  public string Name{get;set;}
}

public class City
{
  public int Id { get; set; }
  public string Name{get;set;}
}

public class MockData
{
    public List<City> GetAllCities()
    {
        return new List<City>(){ new City(){ Id = 11, Name="Delhi"}, new City(){  Id = 22, Name="Mumbai"} };
    }
    
    public List<Country> GetAllCountries()
    {
        return new List<Country>(){ new Country(){ Id=1, Name="India", CityIds = new List<int>(){ 11,22 } } };
    }
}


void Main()
{
    var _database = new MockData();
    List<City> cities = _database.GetAllCities();
    List<Country> countries = _database.GetAllCountries();

    var citiesGroupedByCountry = from p in countries
                                 select new{ Country=p, Cities = cities.Where(x=> p.CityIds.Contains(x.Id)) };
    Console.Write(citiesGroupedByCountry);                               
}

glaga blag blag

  • Related