Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq orderby, start with specific number, then return to lowest

Tags:

I have a set of data which I'd like to re-order starting with a specific number and then, when the highest number is reached, go back to the lowest and then carry on incrementing.

For example, for the sequence (1,2,3,4,5,6), if 4 was the specific number, the order would become (4,5,6,1,2,3).

Is that possible with linq & c#?

like image 413
Howard Shaw Avatar asked Sep 25 '12 09:09

Howard Shaw


People also ask

How do I get data in descending order in LINQ?

OrderByDescending Operator If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.

What is difference between OrderBy and ThenBy in LINQ?

The OrderBy() Method, first sort the elements of the sequence or collection in ascending order after that ThenBy() method is used to again sort the result of OrderBy() method in ascending order.

How do I sort in LINQ?

LINQ includes five sorting operators: OrderBy, OrderByDescending, ThenBy, ThenByDescending and Reverse. LINQ query syntax does not support OrderByDescending, ThenBy, ThenByDescending and Reverse. It only supports 'Order By' clause with 'ascending' and 'descending' sorting direction.

How do I sort a list in ascending order LINQ?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.


2 Answers

List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6 };
int num = 4;
var newList = list.SkipWhile(x=>x!=num)
                    .Concat(list.TakeWhile(x=>x!=num))
                    .ToList();
like image 177
L.B Avatar answered Sep 19 '22 15:09

L.B


int specific = 4;
var numbers = Enumerable.Range(1, 9);

var result = numbers.OrderBy(n => Tuple.Create(n < speficic, n)).ToList();

I use a little trick here, using Tuple<bool, int> as the comparer, since false < true. An alternative is:

var result = numbers.OrderBy(n => n < speficic).ThenBy(n => n).ToList();

EDIT after a benchmark I found the second solution .OrderBy .ThenBy is much faster than the Tuple solution. I believe it's because the FCL uses Comparer<T>.Default as the comparer, which costs time in constructing.

like image 45
Cheng Chen Avatar answered Sep 23 '22 15:09

Cheng Chen