简体   繁体   English

IEnumerable上的递延订单<T>

[英]Deferred OrderBy on IEnumerable<T>

I have this code which just simply sorts IEnumerable of integers based on digit number in each of the integer. 我有这段代码,可以根据每个整数中的位数简单地对IEnumerable整数进行排序。

var ints = new List<int>() { 66, 7, 9, -5, -22, 67, 122, -333, 555, -2 };
var ordered = ints.OrderBy(x =>
{
   x = Math.Abs(x);

   Console.WriteLine($"Getting length of {x}");

   int len = 0;
   while (x >= 1)
   {
      len++;
      x /= 10;
   }
   return len;
});

   Console.WriteLine("After OrderBy");
   Console.WriteLine("Fetching first item in ordered sequence");
   Console.WriteLine($"First item is {ordered.First()}");

   Console.WriteLine(string.Join(" ", ordered));

So, when the program hits line with fetching first item in ordered sequence in that moment the IEnumerable is getting sorted(I'm receiving output lines Getting lenght of XXX ) because OrderBy was deferred and that't quite clear. 因此,该程序,不但有取第一项行时ordered序列中的那一刻了IEnumerable是越来越排序(我收到输出线Getting lenght of XXX ),因为排序依据推迟和that't很清楚。

But why when program hits Console.WriteLine(string.Join(" ", ordered)); 但是,为什么程序点击Console.WriteLine(string.Join(" ", ordered)); I'm again getting this output? 我又得到了这个输出? Is IEnumerable sorted again? IEnumerable是否再次排序? (isn't it already sorted?) (不是已经排序了吗?)

When you assign the value to ordered , they are not actually ordered. 当您将值分配给ordered ,它们实际上并未排序。 It's basically an instruction to order a list. 基本上,这是订购列表的指令。 IOrderedEnumerable<int> . IOrderedEnumerable<int> So each time you try to access the first item, or any other item, it will convert this to an ordered list, to give you that item. 因此,每次您尝试访问第一个项目或任何其他项目时,它都会将其转换为有序列表,从而为您提供该项目。 The first time when you run .First() , and the second time when you run string.Join . 第一次运行.First() ,第二次运行string.Join
In both cases the program will create 2 distinct instances of an ordered list, use it up, then dispose of it by losing the reference (since you're not saving it). 在这两种情况下,程序都会创建一个有序列表的2个不同实例,用完它,然后通过丢失引用来处理它(因为您没有保存它)。

If you need Ordered to be sorted only once, you need to call ToList() on it, in which case you will see the list result only once. 如果需要仅对Ordered排序一次,则需要在其上调用ToList(),在这种情况下,您将仅看到列表结果一次。 Since it ordered. 自下令以来。

var ints = new List<int>() { 66, 7, 9, -5, -22, 67, 122, -333, 555, -2 };
var ordered = ints.OrderBy(x =>
{
    x = Math.Abs(x);

    Console.WriteLine($"Getting length of {x}");

    int len = 0;
    while (x >= 1)
    {
        len++;
        x /= 10;
    }
    return len;
}).ToList();

Console.WriteLine("After OrderBy");
Console.WriteLine("Fetching first item in ordered sequence");
Console.WriteLine($"First item is {ordered.First()}");
Console.WriteLine(string.Join(" ", ordered));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM