Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array sorting by two parameters

Tags:

arrays

c#

I'm having a little difficulty with the array.sort. I have a class and this class has two fields, one is a random string the other one is a random number. If i want to sort it with one parameter it just works fine. But i would like to sort it with two parameters. The first one is the SUM of the numbers(from low to high), and THEN if these numbers are equal by the random string that is give to them(from low to high).

Can you give some hint and tips how may i can "merge" these two kinds of sort?

Array.Sort(Phonebook, delegate(PBook user1, PBook user2)
        { return user1.Sum().CompareTo(user2.Sum()); });
        Console.WriteLine("ORDER");

        foreach (PBook user in Phonebook)
        {
            Console.WriteLine(user.name);
        }

That's how i order it with one parameter.

like image 223
Gregion Avatar asked Dec 08 '22 19:12

Gregion


1 Answers

i think this is what you are after:

sourcearray.OrderBy(a=> a.sum).ThenBy(a => a.random)
like image 106
Behnam Esmaili Avatar answered Dec 11 '22 10:12

Behnam Esmaili