Sorting range of list using LINQ

Deadly 提交于 2020-01-03 03:31:11

问题


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!


回答1:


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));



回答2:


Simply get the required range based on some criteria and apply the sort on the resultant range using Linq.

List<int> numbers = new List<int>() { 15, 4, 1, 3, 2, 11, 7, 6, 12, 13 };
var range = numbers.Skip(3).Take(4).OrderBy(n => n).Select(s => s);
// output: 2, 3, 7, 11



回答3:


List<int> list = new List<int>() {1,2,3,15,11,13,10,6,7};
list.Sort(3, 4,Comparer<int>.Default);



回答4:


Use this for default inline List Sort:

Syntax: List.Sort(start index, number of elements, Default Comparer)

List<int> numbers = new List<int> { 1, 2, 3, 15, 11, 13, 10, 6, 7 };
numbers.Sort(3, 6, Comparer<int>.Default);

If you want to sort by [properties/attributes] of the element or precisely something else use the below method,

I had sorted the string by number of characters, and also from 2nd element to end of List.

Syntax: List.Sort(start index, number of elements, Custom Comparer)

List<string> str = new List<string> { "123", "123456789", "12", "1234567" };
str.Sort(1, str.Count - 1, Comparer<string>.Create((x, y) => x.Length.CompareTo(y.Length)));



回答5:


No, the Linq extension methods will never modify the underlying list. You can use the method List<T>.Sort(int index, int counter, IComparer<T> comparer) to do an in-place sort:

var list = new List<int> {1, 2, 3, 15, 11, 13, 10, 6, 7};
list.Sort(3, 4, null);


来源:https://stackoverflow.com/questions/12874947/sorting-range-of-list-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!