0

I tried to search but I cannot seem to find my answer. I think an answer may exist as it not a uncommon question. I trying to say Sort by Item1. If they are equal, sort by Item2

sorted.Sort((a,b)=>(a.Item1.CompareTo(b.Item1)));
user3398315
  • 331
  • 6
  • 17
  • possible duplicate of [Multiple Order By with LINQ](http://stackoverflow.com/questions/2318885/multiple-order-by-with-linq) – JohnLBevan Jul 07 '14 at 18:55

3 Answers3

2

While you can build a comparer to do this with List<T>.Sort, it's much easier to use LINQ, which is built for this sort of thing:

sorted = unsorted.OrderBy(x => x.Item1).ThenBy(x => x.Item2).ToList();

If you really want to use Sort, you can use the ProjectionEqualityComparer in my MiscUtil project - but it won't be as nice as the LINQ approach.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1
var sorted = original.OrderBy(c => c.Item1).ThenBy(n => n.Item2).ToList()

Try this

TGH
  • 38,769
  • 12
  • 102
  • 135
0

As an alternative to the LINQ methods, you can create a comparer:

class FrobComparer : IComparer<Frob>
{
    public int Compare(Frob x, Frob y)
    {
        int item1Comparison = x.Item1.CompareTo(y.Item1);

        if (item1Comparison == 0)
            return x.Item2.CompareTo(y.Item2);
        return item1Comparison;
    }
}

And then pass that into Sort(), assuming unsorted is a List<Frob>:

var sorted = unsorted.Sort(new FrobComparer());
itsme86
  • 19,266
  • 4
  • 41
  • 57