Search code examples
c#tuplesicomparer

How to compare Tuples with a custom Comparer for entries, but the default Comparer for the Tuple?


I want to sort a List<Tuple<Vertex, Vertex>>, i.e. a list of tuples, where each tuple contains a certain amount of vertices.
Vertex is a custom class, List and Tuple are from System.

I already have several Comparers that provide a way to compare two vertices, e.g.:
class MyVertexComparer1 : Comparer<Vertex> and class MyVertexComparer2 : Comparer<Vertex>

Now I would like to use these existing Comparers to sort the list according to the default tuple comparision, i.e. comparing the first entry and only in case of a tie comparing the next entry.
The comparision of two tuples within this sorting should be determined by one of the custom VertexComparers.

I know I could write a class MyTupleComparer : Comparer<Tuple<Vertex, Vertex>> that uses the MyVertexComparer in its implementation, maybe with a generic parameter that specifies which VertexComparer to use. However, this feels wrong as I would simply repeat the default comparision for tuples.
Moreover, I do not see how this could be extended to tuples with more than two vertices without a dedicated comparer class for each number of vertices.


Solution

  • Make Vertex an IComparable<Vertex>, and the default Sort on List<T> will work as you describe; that is, a default comparer will be used for Tuple, since no custom comparer is provided, and the Vertex.CompareTo method will be used for the entries.

    If you want to reuse your existing Comparers, you can delegate/share the functionality with the IComparable<Vertex>.CompareTo implementation; but you can't do what you want without either writing another Comparer for Tuple (it'd be for each kind of Tuple, since Tuple<T1, T2> is a different type than Tuple<T1, T2, T3>), or implementing IComparable<Vertex> on Vertex type.