在上一篇文章(http://bit.ly/bbIthV)中,我询问当Address可能为null时,如何按其嵌套的Address.State对人员列表进行分组。
Jon Skeet给出了我的问题的完美答案:
//Create a dummy replacement for when a person has no addresses
Address dummyAddress = new Address { State = "" };
people.GroupBy(p => (p.Addresses.GetFirstOrDefault() ?? dummyAddress).State);
但看到结果,我发现我并没有问正确的问题。
如果我有6个人,每个人住在n个地址,上面只会得到6个团体......而我应该得到一组人,按照可以找到的关键状态分组:
var distinctAddresses = people.SelectMany(p=>p.Addresses).City).Distint();
我认为答案将涉及某种类型的GroupJoin,但我还没有走得太远......
//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);
有人建议如何继续吗?
非常感谢!
答案 0 :(得分:0)
使用查询语法可能更简单:
var q = from p in People
group p by p.Address.State into g
select g;
答案 1 :(得分:0)
这个怎么样?
var q =
(from p in people
from a in p.Addresses
group p by a.State ?? "")
.ToDictionary(x => x.Key, x => x.Distinct())