尝试通过使用LINQ对子元素进行分组来创建列表

时间:2016-08-03 17:10:37

标签: c# linq

我有以下课程:

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

城市在运行时填充了他们所有的兴趣。

我需要做的,似乎无法找到如何创建一个不同的兴趣列表,以便我可以显示哪些城市有相同的兴趣。

我尝试过选择和分组,但无法获得理想的结果。

2 个答案:

答案 0 :(得分:1)

您可以先将所有州际公路选入IEnumerable,然后使用Linq的GroupBy扩展来获取IGrouping,其中包含用作标识符作为键和所有城市的州际属性。这是一些伪代码:

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

其中许多内容可以链接到单个LINQ语句中,但我想将其分解为详细并解释每一步。

答案 1 :(得分:0)

您可以创建一个字典,将Interstate映射到拥有该州际公路一部分的城市。首先创建一个不同的Interstate s列表:

List<City> yourCities = ... // populated as you said
List<Interstate> interStates = yourCities.SelectMany(city => city.Interstates).Distinct();

然后通过过滤城市来创建字典:

Dictionary<Interstate, List<City>> interStatesToCities = 
    interStates.ToDictionary(s => s, 
                             s => yourCities.Where(city => city.Interstates.Contains(s)).ToList());

请注意,对于InterstateDistinct的{​​{1}}类,您可能需要进行适当的相等比较才能正常工作。默认情况下,ToDictionary通过引用进行比较。因此,如果您有代表Interstate的不同实例,则可能需要覆盖I-35或实施Equals()