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()));
精彩评论