Use ThenBy
:
var orderedCustomers = Customer.OrderBy(c => c.LastName).ThenBy(c => c.FirstName)
See MSDN: http://msdn.microsoft.com/en-us/library/bb549422.aspx
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);
});
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With