Home > Net >  Ordering Linq list by array elements
Ordering Linq list by array elements

Time:12-15

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:

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.

CodePudding user response:

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();
  • Related