Home > Software engineering >  Custom reorder a list based off another list in C#
Custom reorder a list based off another list in C#

Time:02-16

I have a 2d lists:

{{"Porsche", "Blue"}, {"Ferrari", "Red"}, {"Honda", "Green"}, {"Lambo", "Black"}}

I want to reorder the list based off a custom order of the first child element. So I provide a list maybe that looks like the following:

{"Ferrari", "Honda", "Porsche", "Lambo"} /*or perhaps even:*/ {2,3,1,4}

and it will return the reordered original List in this new order I've given, with the colors intact:

{{"Ferrari", "Red"}, {"Honda", "Green"}, {"Porsche", "Blue"}, {"Lambo", "Black"}}

Is that possible in C#?

CodePudding user response:

Perhaps you can work with the below concept:

Concept:

  1. Cast 2d array to Dictionary<string, List<string>>.
  2. Join with result 1 by key and return the result (Outcome: Nested List / Multidimensional array).
using System.Linq;

var lookup = inputs.Select((value, index) => new { brand = value[0], array = value })
    .ToLookup(x => x.brand, x => x.array);

var order = new List<string>{"Ferrari", "Honda", "Porsche", "Lambo"};
var orderList = (from o in order
    join l in lookup on o equals l.Key
    select l
    ).ToArray();        

Sample program

Output

[["Ferrari","Red"],["Honda","Green"],["Porsche","Blue"],["Lambo","Black"]]

Side note:

In case the 2d array data contains multiple records same brand, then you need .SelectMany() to flatten the result after joining the order array/list and 2d array.

string[][] inputs = new string[][]
{ 
    new string[] {"Porsche", "Blue"}, 
    new string[] {"Ferrari", "Red"}, 
    new string[] {"Honda", "Green"}, 
    new string[] {"Lambo", "Black"},
    new string[] {"Ferrari", "Yellow"}, 
};

var lookup = inputs.Select((value, index) => new { brand = value[0], array = value })
    .ToLookup(x => x.brand, x => x.array);

var order = new List<string>{"Ferrari", "Honda", "Porsche", "Lambo"};
var orderList = (from o in order
    join l in lookup on o equals l.Key
    select l
    )
    .SelectMany(x => x)
    .ToArray();

Sample program (Flatten array for same brands)

  • Related