1

I have a list which I want to sort:

List<string> temp = {
    "Mina 1", "Mina 2", 
    "Planning 3", "Planning 2", "Planning 1", "Planning 4", 
    "Kira 2", "Kira 1"};

List to sort:

// Sort items based on the following order of name
List<string> listToSort= {"Planning", "Mina", "Kira" };

I'm trying to sort temp based on listToSort and number increase

expected Result:

List<string> temp = {
    "Planning 1", "Planning 2", "Planning 3", "Planning 4",
    "Mina 1", "Mina 2",  
    "Kira 1", "Kira 2"};
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
MinhKhai
  • 33
  • 6

2 Answers2

1

Since these are lists you can use a combination of FindIndex and StartsWith:

var result = temp
    .OrderBy(t => listToSort.FindIndex(s => s.StartsWith(t)))
    .ThenBy(t => t);
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
1

While not the most efficient, one option is to use SelectMany:

var sorted = listToSort.SelectMany(sortKey => temp.Where(t => t.StartsWith(sortKey)).OrderBy(s => s));

For every string in listToSort, SelectMany finds all related string in temp and orders by them.

If you need natural sorting (so "Kira 11" will be sorted after "Kira 9"), you can add a comparer, for example Natural Sort Order in C#

Kobi
  • 135,331
  • 41
  • 252
  • 292