2016-08-03 29 views
0

创建列表,我有以下类别:试图通过分组子元素与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; } 
} 

的城市都在运行时填充了所有他们有interestates。

我需要做什么,似乎无法找到如何创建distinc兴趣列表,以便显示哪些城市有相同兴趣。

我试过选择和分组,并且无法得到想要的结果。

+0

“创建一个distinc兴趣列表,以便我可以显示哪些城市有相同的兴趣”。对不起!我很困惑。你想做什么 ?如果你试图得到不同的,你是否尝试'Distinct()'方法? – Shyju

+0

@Shyju我想创建一个新的名单与所有的国家和有兴趣的城市 –

+0

你想要一个州列表或城市名单? – Shyju

回答

1

您可以这样做,首先将所有interstates选择到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语句,但我想打破它是详细解释每一个步骤。

+0

使用你的伪代码,我设法解决了这个问题,谢谢! –

0

您可以创建一个字典映射Interstate s到拥有该州际公路的城市。起初创建的Interstate个不同的列表:

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()); 

请注意,您可能需要为InterstateDistinctToDictionary适当的相等比较正常工作。默认情况下,Interstate按引用进行比较。因此,如果您有代表I-35的不同实例,则可能需要覆盖Equals()或实施IEqualityComparer<Interstate>