Home > front end >  C# sort out 2 values
C# sort out 2 values

Time:01-13

i have a list two values. i want to sort out with priority 1x first. if x1 was big so sort x1 up and if x1 equal big with x1 other so sort based on x2 than smallest.

public class A
{
    public float x1;
    public float x2;
}

public A(float x1, float x2)
{
    this.x1 = x1;
    this.x2 = x2;
}

List<A> sortedA = new List<A>();

sortedA.Add(new A(5, 1));
sortedA.Add(new A(7, 2));
sortedA.Add(new A(4, 3));
sortedA.Add(new A(2, 4));

Example 1

x1 - x2
5 - 1
7 - 2
4 - 3
2 - 4

The sorted list should print as below:

7 - 2
5 - 1
4 - 3
2 - 4

Example 2 if x1 equal with x1 other.

x1 - x2
5 - 2
3 - 1
7 - 5
7 - 2

The sorted list should print as below: if x1 equal with x1 other. Priority x2 Smallest

7 - 2
7 - 5
5 - 2
3 - 1

CodePudding user response:

As pointed out by some comments, OrderBy and ThenBy or OrderByDescending and ThenByDescending are probably what you are looking for

    using System.Linq;
    List<A> list = new List<A>();

    list.Add(new A(5, 1));
    list.Add(new A(7, 2));
    list.Add(new A(4, 3));
    list.Add(new A(2, 4));
    
    var ordered = list
        .OrderByDescending(x => x.x1)
        .ThenByDescending(x => x.x2);
    
    foreach(var val in ordered)
        Console.WriteLine($"{val.x1} - {val.x2}");  

Output:

result

C# Fiddle

CodePudding user response:

You can use the List.Sort() method with a custom IComparer implementation to sort the list based on your criteria.

Here's an example implementation of the IComparer class:

class CompareA : IComparer<A>
{
    public int Compare(A a1, A a2)
    {
        if (a1.x1 > a2.x1)
        {
            return -1;
        }
        else if (a1.x1 < a2.x1)
        {
            return 1;
        }
        else
        {
            if (a1.x2 < a2.x2)
            {
                return -1;
            }
            else if (a1.x2 > a2.x2)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
    }
}

Then you can use the following code to sort the list:

sortedA.Sort(new CompareA());

This will sort the list in descending order based on x1, and ascending order based on x2 in case of equal x1 values

CodePudding user response:

If you want to sort existing list, just Sort it; the only thing we have to do is to explain how to compare two items a and b:

sortedA.Sort((a, b) => {
  int order = b.x1.CompareTo(a.x1);

  return order != 0         // if we haven't got tie ...
    ? order                 //   ... return result 
    : a.x2.CompareTo(b.x2); //   on tie compare x2's
});

Here we used a simple trick for sorting in descending order:

b.x1.CompareTo(a.x1) // descending order, note a and b swapped
a.x2.CompareTo(b.x2) // ascending order, business as usual
  • Related