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#?
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.
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.
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.
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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With