In order to sort a collection of objects based on another list that contains the proper order, we can create an extension method that performs a `Join` between these two collections and pass a `func` as innerKeySelector  argument to allow us to sort this collection based on whatever key we want.

[gist id=”c1b6681e3e04c0d1d928″]

Example

// Object that we are going to use
class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
}

// Initialize a collection of objects
var items = new List<Item>
{
    new Item {Id = 1, Name = "Item 1"},
    new Item {Id = 3, Name = "Item 3"},
    new Item {Id = 5, Name = "Item 5"},
    new Item {Id = 2, Name = "Item 2"}
};

// Sort items based on the following order of ids
var sortedIds = new[] { 1, 2, 5, 3 };

// Sort items based on the following order of ids
var sortedNames = new[] { "Item 1", "Item 5", "Item 3" };

var sortedById = items.SortBy(sortedIds, c => c.Id);
var sortedByName = items.SortBy(sortedNames, c => c.Name);

// Result
{
  "sortedById": [
    {
      "id": 1,
      "name": "Item 1"
    },
    {
      "id": 2,
      "name": "Item 2"
    },
    {
      "id": 5,
      "name": "Item 5"
    },
    {
      "id": 3,
      "name": "Item 3"
    }
  ],
  "sortedByName": [
    {
      "id": 1,
      "name": "Item 1"
    },
    {
      "id": 5,
      "name": "Item 5"
    },
    {
      "id": 3,
      "name": "Item 3"
    }
  ]
}

 

Categorized in:

Tagged in: