Home > Enterprise >  C# sorting two lists alphanumerically
C# sorting two lists alphanumerically

Time:04-07

I have two lists where the first list are headers and the second list are values that corresponds to these headers. I will like to sort the headers alphanumerically but I do not know how I can solve this. Since the values in the second list needs to be sorted out accordingly. For example

var columns = new List<string> { "Name", "Age", "Height", "1stRegistration" };
var values  = new List<string> { "Bob", "27", "1.8", "01-01-2022" };

using the Sort() method on the list will produce the following result but how do i get the values to be sorted based on the results?

1stRegistration     ---> 01-01-2022 // expected values in the second list
Age                 ---> 27
Height              ---> 1.8
Name                ---> Bob

CodePudding user response:

The easiest option is to pair these together before you sort. You can do this using LINQ:

var sorted = columns.Zip(values).OrderBy(x => x.First);

foreach (var (column, value) in sorted)
{
    Console.WriteLine($"{column,-20} ---> {value}");
}

Output:

1stRegistration      ---> 01-01-2022
Age                  ---> 27
Height               ---> 1.8
Name                 ---> Bob

CodePudding user response:

Since column must correspond its value you can combine both lists

var columnAndValue = new List<(string column, string value)> {
  ("Name", "Bob"),
  ("Age", "27"),
  ("Height", "1.8"),
  ("1stRegistration", "01-01-2022"),
};

and then Sort as

columnAndValue.Sort((left, right) => left.column.CompareTo(right.column));

If you insist on having two lists, you can combine them temporary with a help of Zip:

var both = colums
  .Zip(values, (c, v) => (column : c, value : v))
  .OrderBy(pair => pair.value)
  .ToList();

colums.Clear();
values.Clear();

columns = both.AddRange(both.Select(pair => pair.column));
values = both.AddRange(both.Select(pair => pair.value));
  •  Tags:  
  • c#
  • Related