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.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | // 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" } ] } |