Reputation: 7124
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 [email protected]).
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:
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:
How can I get my list sorted to look like the above desired result?
Upvotes: 1
Views: 577
Reputation: 27282
If you use LINQ, you can do it like this:
var sortedList = list.OrderBy( x => x.LastName ?? x.EntityName );
Upvotes: 2
Reputation: 17428
You could do this:
list.Sort(delegate(ClientContact c1, ClientContact c2)
{
return !string.IsNullOrEmpty(c1.LastName) ?
c1.LastName.CompareTo(c2.LastName) :
c1.EntityName.CompareTo(c2.LastName);
});
Upvotes: 0
Reputation: 726559
Try using this comparison instead:
(c1.LastName ?? c1.EntityName).CompareTo(c2.LastName ?? c2.EntityName)
Upvotes: 6