Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort just part of a huge list using .NET?

In .NET, the Generics Lists have a sort function that accepts IComparer or Comparison. I'd like to sort just part of a list. Hopefully I can specify the start index, count of elements to sort, and a lambda function. It looks like you can only use lambda functions to do this if you're sorting the entire list. Is that right or did I miss something?

Additional Requirements:

  • Sort in place (to save memory/time)
  • Final list has the same length as the original list
like image 603
Eyal Avatar asked Nov 19 '25 00:11

Eyal


2 Answers

List<int> mylist = new List<int>() {8,4,6,2,1,5,3,1,7};
List<int> myRange = mylist.GetRange(2,4);

mylist.RemoveRange(2, 4);
mylist.InsertRange(2,  myRange.OrderBy(i => i));

mylist.Dump();

EDIT: Think of Dump as running a foreach on the list & printing it to the console.
And this is changing the content of the original list.

EDIT2: See if this code helps at all

    List<int> mylist = new List<int>() ;
    for(int i=9999999; i > 0; i--)
    {
        mylist.Add(i);
    }

    Console.WriteLine("start " + DateTime.Now.Ticks);
    var extract = mylist.Skip(10).Take(1000000).OrderBy(i => i);

    int k = 10; // start from (because we skipped from 10 onwards above)
    foreach(int item in extract)
    {
        mylist[k++] = item;
    }


    Console.WriteLine("done" + DateTime.Now.Ticks);
    foreach(int item in mylist)
        Console.WriteLine(item);
like image 78
shahkalpesh Avatar answered Nov 20 '25 13:11

shahkalpesh


Instead of RemoveRange and InsertRange you could extract the sublist, and the copy it back. Yes, I know, this isn’t in-place either but short of rewriting Sort you won’t find such a solution.

Dim myList As New List<int>() { 8, 4, 6, 2, 1, 5, 3, 1, 7 }
Dim myRange = myList.GetRange(2,4)

myRange.Sort(yourComparer)
Dim i = 2;
For Each item in myRange
    mylist(i) = item
    i += 1
Next
like image 31
Konrad Rudolph Avatar answered Nov 20 '25 12:11

Konrad Rudolph



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!