Home > Blockchain >  Sort string array according to priority array
Sort string array according to priority array

Time:12-26

I have a priority list

List<string> priority = new List<string>() {
              "boss",
              "Project owner",
              "client",
              "manager",
              "client1",
              "client2 ",
              "Intern",
          };

and i want to sort other array according to this priority

List<string> arr = new List<string>(){ "client1", "boss", "manager" }
priority.Sort(arr);

it should return ["boss", "manager", "client1"]

note: There can be other items which are not in Priority so we can put them in last.

CodePudding user response:

In the priority list, the client 1 item apparently has an extra space. However, you can sort the array according to the index in the priorit list:

        List<string> priority = new List<string>() {
          "boss",
          "Project owner",
          "client",
          "manager",
          "client1",
          "client2 ",
          "Intern",
      };

     List<string> arr = new List<string>() { "client1", "boss", "manager" };

     var result= arr.OrderBy(x => Array.IndexOf(priority.ToArray(), x)).ToList();

CodePudding user response:

  1. Create an anonymous list with Value and Order (Get the index from the priority array) properties.

  2. Order by descending for those which Order is not -1 first. Those Order with -1 will be placed at last.

  3. Then order by Order (ascending).

  4. Get the Value only to return a list of strings.

List<string> sortedArr = arr.Select(x => new 
    {
        Value = x,
        Order = priority.IndexOf(x)
    })
    .OrderByDescending(x => x.Order != -1)
    .ThenBy(x => x.Order)
    .Select(x => x.Value)
    .ToList();

Demo @ .NET Fiddle

CodePudding user response:

I used this, and I got the correct result. I was wondering if it contains any corner cases left or any flaws still left.

  List<string> priority = new List<string>() {
          "boss",
          "Project owner",
          "client",
          "manager",
          "client1",
          "client2 ",
          "Intern",
      };

  List<string> arr = new List<string>() { "client1", "boss", "manager" };

  arr.Sort((a, b) => {
      if (priority.Contains(a))
           {
              return -1;
           };
       if (priority.Contains(b))
          {
             return 1;
          };
     return 0;
 });

CodePudding user response:

you can use the OrderBy to sort.

List<string> priority = new List<string>() {
        "boss",
        "Project owner",
        "client",
        "manager",
        "client1",
        "client2 ",
        "Intern",
    };

List<string> arr = new List<string>() { "client1", "boss", "manager" };
List<string> sortedArr = arr.OrderBy(x => priority.IndexOf(x)).ToList();

There was a typo in your code, client 1 should be client1 in the priority list.

  • Related