I have a question:
For example I have 2 lists:
1: Banana
Apple
Orange
2: Yellow
Red
Orange
I want it to list.sort
so it will be:
Apple
Banana
Orange
But in the same time I want the SAME changes happening inside of the Yellow red orange list.
So it would be like this:
Apple
Banana
Orange
Red
Yellow
Orange
I didnt try this because I literally have no idea how to do this and all this is just on the planning board
CodePudding user response:
You should really start using classes which encapsulate these information in one entity, for example:
public class Fruit
{
public string Name {get; set;}
public string Color {get; set;}
}
Then it's easy and readable:
List<Fruit> fruits = new()
{
new Fruit{ Name = "Banana", Color = "Yellow" },
new Fruit{ Name = "Apple", Color = "Red" },
new Fruit{ Name = "Orange", Color = "Orange" }
};
var orderedFruits = fruits.OrderBy(f => f.Name);
If you want to sort the original list, simply append ToList
ad re-assign it:
fruits = fruits.OrderBy(f => f.Name).ToList();
If you really must use two separate lists which depend on each other, you could use Zip
:
List<string> fruitNames = new() { "Banana", "Apple", "Orange" };
List<string> fruitColors = new() { "Yellow", "Red", "Orange" };
List<(string Name, string Color)> orderedFruits = fruitNames
.Zip(fruitColors, (n, c) => (Name: n, Color: c))
.OrderBy(x => x.Name)
.ToList();
fruitNames = orderedFruits.Select(x => x.Name).ToList();
fruitColors = orderedFruits.Select(x => x.Color).ToList();
CodePudding user response:
You could try to zip
the two list, making a list of pairs.
Then you can apply a custom sort
on this list of pair, sorting pairs only relatively to the first element.
Once the sort is done, you can unzip
the list of pairs to get back your two lists, sorted the same way.
CodePudding user response:
If for some reason it is problematic to merge the lists, say you have a large list of large structs for example, an alternative can be to use a proxy list with indices for sorting:
var fruits = ...
var colors = ...
var proxy = Enumerable.Range(0, fruits.Length);
var sortedProxy = proxy.OrderBy(i => fruits[i]);
var sortedColors = sortedProxy.Select(i => colors[i]).ToList();
This lets you sort the indices according to the order defined by one list, and then you can use this ordering to create an ordered list for any list of the same length. Note that this example leaves the fruit list unordered.
You can reduce allocations by creating a custom comparer that does the i => fruits[i]
-part so that you can use List.Sort
instead of OrderBy.