Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting range of list using LINQ

I was wondering if it is possible to do ranged sort using LINQ, for example i have list of numbers:

List< int > numbers = new List< int >

  • 1
  • 2
  • 3
  • 15 <-- sort
  • 11 <-- sort
  • 13 <-- sort
  • 10 <-- sort
  • 6
  • 7
  • etc.

Simply using numbers.Skip(3).Take(4).OrderBy(blabla) will work, but it will return a new list containing only those 4 numbers. Is is somehow possible to force LINQ to work on itself without returning a new "partial" list or to receive complete one with sorted part? Thanks for any answer!

like image 268
Marduk Avatar asked Oct 25 '25 22:10

Marduk


2 Answers

Try something like this:

var partiallySorted = list.Where(x => x < 11)
                 .Concat(list.Where(x => x >= 11 && x <=15).OrderBy(/*blah*/)))
                 .Concat(list.Where(x => x > 15));
like image 198
Steven Evers Avatar answered Oct 28 '25 16:10

Steven Evers


List<int> list = new List<int>() {1,2,3,15,11,13,10,6,7};
list.Sort(3, 4,Comparer<int>.Default);
like image 35
L.B Avatar answered Oct 28 '25 15:10

L.B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!