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)));
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)));
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.
var sorted = original.OrderBy(c => c.Item1).ThenBy(n => n.Item2).ToList()
Try this
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());