Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ordering Linq list by array elements

I have below code –

var refNosToOrder = new int[9] {1,2,3,4,5,6,7,8,9}

var orderedList = lst.OrderBy(x=>x.RefNo==7)
                     .ThenBy(y=> refNosToOrder.Contains(y.RefNo)).ToList();

lst is list of class object containing int property – RefNo : i.e. List<SampleClass>

class SampleClass
{
  public int RefNo {get;set;}
}

lst contains all the unsorted data of RefNo:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

lst = 2,4,6,9,7,5,8,1,3

What I want to do –

First I want to order lst by keeping first element as – 7; then for the rest of the list, it should be ordered as the array refNosToOrder

i.e. Final output I am expecting to be –

7,1,2,3,4,5,6,8,9

With the above code –

var orderedList = lst.OrderBy(x=>x.RefNo==7)
                         .ThenBy(y=> refNosToOrder.Contains(y.RefNo)).ToList();

It is giving – 2,4,6,9,7,5,8,1,3 i.e. this code is not at all ordering the list.

>Solution :

Contains returns a boolean of whether an element is in a list or not, which won’t be very helpful here. Instead, you could sort by the index of that element:

var orderedList = 
    lst.OrderBy(x => x.RefNo != 7)
       .ThenBy(y => Array.IndexOf(refNosToOrder, y.RefNo))
       .ToList();

EDIT:
Following up on Jeroen Mostert’s comment, this sorting has quadratic complexity. For large refNosToOrder it may be more efficient to first convert the array to a dictionary of orders and then use it for the sorting:

var orderDict = 
    Enumerable.Range(0, refNosToOrder.Length).ToDictionary(i => refNosToOrder[i]);
var orderedList = 
    lst.OrderBy(x => x.RefNo != 7).ThenBy(y => orderDict[y.RefNo]).ToList();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading