CptSupermrkt
CptSupermrkt

Reputation: 7124

Sorting a List by two variables

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:

  1. Bond James
  2. Customer Support
  3. Gates Bill
  4. Tech Support
  5. 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:

  1. Customer Support
  2. Tech Support
  3. Bond James
  4. Gates Bill
  5. Williams Robin

How can I get my list sorted to look like the above desired result?

Upvotes: 1

Views: 577

Answers (3)

Ethan Brown
Ethan Brown

Reputation: 27282

If you use LINQ, you can do it like this:

var sortedList = list.OrderBy( x => x.LastName ?? x.EntityName );

Upvotes: 2

pstrjds
pstrjds

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

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

Try using this comparison instead:

(c1.LastName ?? c1.EntityName).CompareTo(c2.LastName ?? c2.EntityName)

Upvotes: 6

Related Questions