问题
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