试图通过使用LINQ对子元素进行分组来创建列表
本文关键字:列表 创建 元素 LINQ | 更新日期: 2023-09-27 17:59:57
我有以下类:
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; }
}
城市在运行时充满了他们所有的兴趣。
我需要做的,似乎找不到如何做,就是创建一个不同兴趣的列表,这样我就可以显示哪些城市有相同的兴趣。
我尝试了选择和分组,但无法获得所需的结果。
您可以先将所有州际公路选择到IEnumerable中,然后使用Linq的GroupBy扩展来获得一个IGrouping,该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语句中,但我想把它分解为冗长的内容,并解释每一步。
您可以创建一个字典,将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());
请注意,您可能需要对Distinct
和ToDictionary
的Interstate
类进行适当的相等比较才能正常工作。默认情况下,Interstate
通过引用进行比较。因此,如果您有代表I-35
的不同实例,则可能需要重写Equals()
或实现IEqualityComparer<Interstate>
。