Order a List (C#) by many fields?

137,205

Solution 1

Use ThenBy:

var orderedCustomers = Customer.OrderBy(c => c.LastName).ThenBy(c => c.FirstName)

See MSDN: http://msdn.microsoft.com/en-us/library/bb549422.aspx

Solution 2

Yes, you can do it by specifying the comparison method. The advantage is the sorted object don't have to be IComparable

   aListOfObjects.Sort((x, y) =>
   {
       int result = x.A.CompareTo(y.A);
       return result != 0 ? result : x.B.CompareTo(y.B);
   });

Solution 3

Make your object something like

public class MyObject : IComparable
{
    public string a;
    public string b;

    virtual public int CompareTo(object obj)
    {
        if (obj is MyObject)
        {
            var compareObj = (MyObject)obj;
            if (this.a.CompareTo(compareObj.a) == 0)
            {
                // compare second value
                return this.b.CompareTo(compareObj.b);
            }
            return this.a.CompareTo(compareObj.b);
        }
        else
        {
            throw new ArgumentException("Object is not a MyObject ");
        }
    }
}

also note that the returns for CompareTo :

http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx

Then, if you have a List of MyObject, call .Sort() ie

var objList = new List<MyObject>();
objList.Sort();
Share:
137,205
Esabe
Author by

Esabe

Updated on January 13, 2021

Comments

  • Esabe
    Esabe over 3 years

    I want to order a List of objects in C# by many fields, not just by one. For example, let's suppose I have a class called X with two Attributes, A and B, and I have the following objects, in that order:

    object1 => A = "a", B = "h"
    object2 => A = "a", B = "c"
    object3 => A = "b", B = "x"
    object4 => A = "b", B = "b"

    and I want to order the list by A attribute first, and when they are equals, by B element, so the order would be:

    "a" "c"
    "a" "h"
    "b" "b"
    "b" "x"

    As far as I know, the OrderBy method order by one parameter.

    Question: How can I order a C# List by more than one field?

  • Jason Jong
    Jason Jong about 14 years
    Question: How can I order a C# List by more than one field? YES !
  • Danimal111
    Danimal111 over 7 years
    This did not order them for me? What am I missing?docs.OrderBy(o => o.AcctNum) .ThenBy(o => o.DocDate);
  • Brad B.
    Brad B. over 7 years
    You may be using an older .net. Check this answer: stackoverflow.com/questions/289010/….
  • Pseudonymous
    Pseudonymous almost 7 years
    For posterity: OrderBy doesn't sort the original collection, it returns an IOrderedEnumerable<T>, so you need to assign the results of OrderBy to a variable. e.g. customers = customers.OrderBy(c=>c.Surname).ThenBy(c.Forename).ToList();