How to sort in C# a tuple that contains several elements?

Edouard Durand 1 Reputation point
2022-04-11T21:41:16.697+00:00

Hi,

I would like to sort in ascending order a tuple starting from its 2nd element:

List<Tuple<string, string, string>> tupleSpecial = new List<Tuple<string, string, string>>

The 2nd element of this tuple actually represents a number, it is stored here as a string, but the sorting would be done according to this 2nd element.

I have already thought of reconstructing a tuple by converting the 2nd element to an int, which would give for example:

List<Tuple<string, int, string>> tupleSpecialInt = new List<Tuple<string, int, string>>

The problem is that as this tuple has 3 elements, I don't see how to sort in ascending order this tuple according to its 2nd element.

How to sort in C# this tuple in ascending order based on its 2nd element (int)?

Thank you for your help.

Windows 10
Windows 10
A Microsoft operating system that runs on personal computers and tablets.
10,808 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,459 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,380 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Ken Tucker 5,846 Reputation points
    2022-04-11T23:58:00.62+00:00

    You could use a custom comparer class

            Tuple<string, int, string>[] lst =
             {
                new Tuple<string, int, string>("z", 1, "z"),
                new Tuple<string, int, string>("a", 2, "a"),
                new Tuple<string, int, string>("d", -1, "d")
            };
            Array.Sort(lst, new MyTupleComparer());
            foreach (var item in lst)
            {
                Console.WriteLine(item.Item2);
            }
    
    
    
    public class MyTupleComparer : Comparer<Tuple<string, int, string>>
    {
        public override int Compare(Tuple<string, int, string> x, Tuple<string, int, string> y)
        {
            return x.Item2.CompareTo(y.Item2);
        }
    }
    
    0 comments No comments

  2. Bruce (SqlWork.com) 57,886 Reputation points
    2022-04-12T16:32:10.76+00:00

    almost correct, to sort by second & third item:

    Tuple<string, int, string>[] lst =
    {
        new Tuple<string, int, string>("z", 1, "z"),
        new Tuple<string, int, string>("a", 2, "a"),
        new Tuple<string, int, string>("a", 2, "b"),
        new Tuple<string, int, string>("d", -1, "d")
    };
    Array.Sort(lst, (x , y) =>
    {
        var c1 = x.Item2.CompareTo(y.Item2);
        return c1 == 0 ? x.Item3.CompareTo(y.Item3) : c1;
    });
    foreach (var item in lst)
    {
        Console.WriteLine($"{item.Item2},{item.Item3}");
    }
    
    0 comments No comments