开发者

How do Group by a child property of a child property that may be null?

How could I go about grouping the following?

people.GroupBy(p=>p.Addresses.GetFirstOrDefault().State);

without it failing on people who don't have an Address?

  • can it be done in one statement?
  • if not, do I have to first get a Distinct() list of all the various addresses members? How? (actually -- even if a is possible -- would be great to also learn how to do b :-) )
  • I havn't see开发者_如何学Cn it, but is there something equivalent to a GetFirstOrNew() that can be used to instantiate and return a non-null?

Thank you very much!


It can be done in one statement, yes:

// Set up whatever you need
Address dummyAddress = new Address { State = "" };

people.GroupBy(p => (p.Addresses.GetFirstOrDefault() ?? dummyAddress).State);

Alternatively, you might want to write a helper method:

public string GetState(Address address)
{
    return address == null ? null : address.State;
}

Then you can use:

people.GroupBy(p => GetState(p.Addresses.GetFirstOrDefault()));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜