Here is a LINQ tip where you may wish to order a collection with an existing ordering of another collection.
Example:
1 2 3 4 5 6 7 8 9 |
int[] displaySeq = new int[] { 1, 8, 5, 7, 13 }; //the ordering we want at the end //collection that we will be sorting on List<Person> people = new List<Person>(); 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.
1 2 |
//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.
1 2 3 4 5 6 7 |
//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 < 0 ? int.MaxValue : index; }).ToList(); |
Thanks! This was exactly what I was looking for!
Thank you so much..i was looking for this.
Nice man, exactly what I needed!
Almost 6 years later and this is still useful. thanks!
Thanks, this is what i am looking for