Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
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:

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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();
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!