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 for business Windows Client for IT Pros User experience Other
Developer technologies .NET Other
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Ken Tucker 5,861 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) 77,686 Reputation points Volunteer Moderator
    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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.