2

I have a List products; with 100+ items.

For each item from the list I have product id.

And I have an array int[] sortedArray = {3,6,22,98,6,45,87};

I have to sort my product list and make order by productid, how it is in sortedArray. How can I implement that?

Thanks in Advance!

1
  • What is in sortedArray? Is it indices, or product IDs? Commented Jan 27, 2020 at 12:05

1 Answer 1

2

One possible approach could be using OrderBy method by passing a Func which uses IndexOf method in order to sort the list based on the sortedArray.

list.OrderBy(s => sortedArray.IndexOf(s.ProductId)).ToList();
Sign up to request clarification or add additional context in comments.

2 Comments

Watch out though - this is an O(N^2.Log(N)) operation which is going to be nasty on large data sets.
@MatthewWatson, Then we could create a hash structure or dictionary in order to access the element with O(1)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.