How do I group by a Nested property's Nested property (part II)
In a previous post (http://bit.ly/bbIthV) i asked how to Group a list of Persons by their nested Address.State, when Address might be null.
Jon Skeet gave a perfect answer to my question:
//Create a dummy replacement for when a person has no addresses
Address dummyAddress = new Address { State = "" };
people开发者_Go百科.GroupBy(p => (p.Addresses.GetFirstOrDefault() ?? dummyAddress).State);
But seeing the results, I see that I wasn't asking the right quesion.
If I have 6 people, each one living at n addresses, the above will only get 6 groups...whereas I should instead be getting a group of persons, grouped by the key State that could be found by:
var distinctAddresses = people.SelectMany(p=>p.Addresses).City).Distint();
I think the answer will involve a GroupJoin of some kind, but I haven't gotten very far...
//Back where I started:
var y = addresses.GroupJoin(persons,a => a.State, p => p.Addresses.FirstOrDefault(),
(a,p)=> p);
//Doesn't compile...
var y = addresses.GroupJoin(persons,a => a, p => p.Addresses, (a,p)=> p);
Does anybody have a suggestion on how to proceed?
Thank you very much!
It might be simpler using query syntax:
var q = from p in People
group p by p.Address.State into g
select g;
How about this?
var q =
(from p in people
from a in p.Addresses
group p by a.State ?? "")
.ToDictionary(x => x.Key, x => x.Distinct())
精彩评论