Order a List (C#) by many fields?

C#ListLambdaSql Order-By

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

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();

Solution 4 - C#

Your object should implement the IComparable interface.

With it your class becomes a new function called CompareTo(T other). Within this function you can make any comparison between the current and the other object and return an integer value about if the first is greater, smaller or equal to the second one.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEsabeView Question on Stackoverflow
Solution 1 - C#David NealeView Answer on Stackoverflow
Solution 2 - C#CMinusView Answer on Stackoverflow
Solution 3 - C#Jason JongView Answer on Stackoverflow
Solution 4 - C#OliverView Answer on Stackoverflow