X

LINQ tip – Ordering collection using existing array/collection using OrderBy

linq

Here is a LINQ tip where you may wish to order a collection with an existing ordering of another collection.

Example:

int[] displaySeq = new int[] { 1, 8, 5, 7, 13 }; //the ordering we want at the end

//collection that we will be sorting on
List people = new List();
people.Add(new Person { DisplaySeq = 5});
people.Add(new Person { DisplaySeq = 13});
people.Add(new Person { DisplaySeq = 7});
people.Add(new Person { DisplaySeq = 1});
people.Add(new Person { DisplaySeq = 8});

Currently as it stands our data is stored in the order of { 5, 13, 7, 1, 8 } and we wish to order them in terms of { 1, 8, 5, 7, 13 }, we can use LINQ OrderBy to do so.


//use the displaySeq array and find the index of it
var sorted = people.OrderBy(x => { return Array.IndexOf(displaySeq, x.DisplaySeq); }).ToList();

By doing so we end up with { 1, 8, 5, 7, 13 }, now if we wanted to put elements that dont have matching at the end of the list we can modify the OrderBy like this.


//add another person that is not part of the displaySeq array
people.Add(new Person { DisplaySeq = 99});

var sorted = people.OrderBy(x => { 
   var index = Array.IndexOf(displaySeq, x.DisplaySeq);
   return index 

Categories: .NET C#
Taswar Bhatti:

View Comments (5)

Related Post