Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Multiple Lists

Tags:

c#

sorting

I have 3 List containing : Index, Name, Age

Example:

List<int> indexList = new List<int>();
indexList.Add(3);
indexList.Add(1);
indexList.Add(2);
List<string> nameList = new List<string>();
nameList.Add("John");
nameList.Add("Mary");
nameList.Add("Jane");
List<int> ageList = new List<int>();
ageList.Add(16);
ageList.Add(17);
ageList.Add(18);

I now have to sort all 3 list based on the indexList.

How do I use .sort() for indexList while sorting the other 2 list as well

like image 471
Bloopie Bloops Avatar asked May 04 '15 15:05

Bloopie Bloops


People also ask

How do you sort 3 lists in Python?

sort() Syntax The syntax of the sort() method is: list.sort(key=..., reverse=...) Alternatively, you can also use Python's built-in sorted() function for the same purpose.

Can you sort a list of lists in Python?

Python List sort() Method Syntax. The Python sort() method sorts the elements of a list in a given order, including ascending or descending orders. The method works in place, meaning that the changed list does not need to be reassigned in order to modify the list.


2 Answers

You are looking at it the wrong way. Create a custom class:

class Person
{
     public int Index { get; set; }
     public string Name{ get; set; }
     public int Age{ get; set; }
}

Then, sort the List<Person> with the help of the OrderBy method from the System.Linq namespace:

List<Person> myList = new List<Person>() {
    new Person { Index = 1, Name = "John", Age = 16 };
    new Person { Index = 2, Name = "James", Age = 19 };
}
...

var ordered = myList.OrderBy(x => x.Index);

Also, you can read Jon Skeet article about your anti-pattern.

like image 154
Farhad Jabiyev Avatar answered Sep 30 '22 07:09

Farhad Jabiyev


Farhad's answer is correct and should be accepted. But if you really have to sort three related lists in that way you could use Enumerable.Zip and OrderBy:

var joined = indexList.Zip(
        nameList.Zip(ageList, (n, a) => new { Name = n, Age = a }), 
            (ix, x) => new { Index = ix, x.Age, x.Name })
        .OrderBy(x => x.Index);
indexList = joined.Select(x => x.Index).ToList();
nameList = joined.Select(x => x.Name).ToList();
ageList = joined.Select(x => x.Age).ToList();

All are ordered by the value in the index-list afterwards.

like image 41
Tim Schmelter Avatar answered Sep 30 '22 08:09

Tim Schmelter