Got a List of “ClientContacts” — which have EITHER a LastName (in the case of a human) OR an EntityName (in the case of a general-use contact, such as techsupport@mycompany.com).
What I want to do is SORT this List alphabetically by LastName, and in the case where no LastName exists (in other words, an EntityName exists), to treat that EntityName as a LastName, and continue the Sort as if it were a LastName.
So that the desired result looks like:
- Bond James
- Customer Support
- Gates Bill
- Tech Support
- Williams Robin
This causes a crash, because it runs into some ClientContacts that don’t have a LastName.
clientContactList.Sort(
delegate(ClientContact c1, ClientContact c2)
{ return c1.LastName.CompareTo(c2.LastName); });
And the following allows me to get through without crashing, and it sorts it by ClientContact EntityName’s first, and THEN LastNames:
list.Sort(delegate(ClientContact c1, ClientContact c2) {
try
{
return c1.LastName.CompareTo(c2.LastName);
}
catch
{
try
{
return c1.EntityName.CompareTo(c2.LastName);
}
catch
{
return c1.EntityName.CompareTo(c2.EntityName);
}
}
});
resulting in:
- Customer Support
- Tech Support
- Bond James
- Gates Bill
- Williams Robin
How can I get my list sorted to look like the above desired result?
Try using this comparison instead: