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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With