LINQ: how to group by so element can be added to many groups

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 03:25:33

问题


I have 3 types: Parameter, Facility and Location. Parameter has one Facility and Facility is related many-to-many with Location. So, if we make a join, we can get such a table:

ParamId FacilityId LocationId
1            1          1
1            1          2
2            2          1
2            2          3

Now i want to group my parameters by locations so that i get a Dictionary>, like this:

LocationId   Parameters
     1          1,2
     2           1
     3           2

I can't do a straight GroupBy because i don't know how to write a keySelector. I Also tried SelectMany like this:

parametersList.SelectMany(t=>t.Facility.Locations).GroupBy(t =>t)
.ToDictionary(t=>t.Key, t=>t.Select(val=>val))

but it cannot form me my Dictionary..

Update: Here is how my Facility (simplified) looks like:

public class Facility
{
    public int Id { get; set; }
    public ICollection<Location> Locations { get; set; }
}

and here is Location:

public class Location
{
    public int Id { get; set; }
    public ICollection<Facility> Facilities { get; set; }
}

I'll be gratefull for any help!


回答1:


This query return that you want:

parametersList
        .SelectMany(_ => _.Facility.Locations)
        .GroupBy(_ => _)
        .ToDictionary(
            _ => _.Key, 
            _ => _.SelectMany(l => l.Facilities).SelectMany(f => f.Parameters).Distinct().ToArray());

UPDATE

You can use parametersList or store of parameters for it:

parametersList
        .SelectMany(_ => _.Facility.Locations)
        .GroupBy(_ => _)
        .ToDictionary(
            _ => _.Key, 
            _ => _.SelectMany(l => l.Facilities).Select(f => parametersList.Single(p => p.Facility == f)).Distinct().ToArray());


来源:https://stackoverflow.com/questions/28109832/linq-how-to-group-by-so-element-can-be-added-to-many-groups

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!