Bruno Xavier Bruno Xavier - 4 months ago 15
C# Question

Trying to create a list by grouping child elements with LINQ

I have the following classes:

public class City
{
public string cityName { get; set; }
public string stateName { get; set; }
public int population { get; set; }

public List<Interstate> Interstates { get; set; }
}

public class Interstate
{
public int interstateName { get; set; }

public string interestateString
{
get { return "I-" + interstateName; }
}

public City city { get; set; }
}


The cities are populated at runtime with all the interestates they have.

What I need to do, and can't seem to find how, is to create a list of distinc interestates so I can show which cities have the same interestates.

I tried selecting and grouping and can't get the desired results.

DVK DVK
Answer

You could do this by first selecting all of the interstates into an IEnumerable, and then using Linq's GroupBy extension to get an IGrouping which would contain the interstate property you use for an identifier as the key and all of the cities. Here is some pseudo-code:

// Get all of your cities
List<City> allCities = GetAllCities();

// Get all interstates
IEnumerable<Interstate> allInterstates = allCities.SelectMany(c => c.Interstates);

// Now group your Interstates
IEnumerable<IGrouping<int, Interstate>> interstateGroups = allInterstates.GroupBy(i => i.interstateName);

// Now you can iterate through your group
foreach(IGrouping<int, Interstate> group in interstateGroups)
{
    // Get all the cities for this particular group which represents all interstates with the same name
    IEnumerable<City> citiesForThisInterstate = group.Select(g => g.Cities);
}

A lot of this could be chained into a single LINQ statement, but I wanted to break it out to be verbose and explain each step.

Comments