对于环和LINQ的延迟执行不玩好起来 [英] For-Loop and LINQ's deferred execution don't play well together

查看:147
本文介绍了对于环和LINQ的延迟执行不玩好起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题表明,我已经一个想法,这是怎么回事,但我无法解释。我试图订购名单,LT;字符串[]> 动态每个列,先上和最小结束长度所有阵列。

The title suggests that i've already an idea what's going on, but i cannot explain it. I've tried to order a List<string[]> dynamically by each "column", beginning with the first and ending with the minimum Length of all arrays.

所以这个样品是在 2 ,因为最后的String [] 只有两个元素:

So in this sample it is 2, because the last string[] has only two elements:

List<string[]> someValues = new List<string[]>();
someValues.Add(new[] { "c", "3", "b" });
someValues.Add(new[] { "a", "1", "d" });
someValues.Add(new[] { "d", "4", "a" });
someValues.Add(new[] { "b", "2" });

现在我已经尝试由第一和第二列订制。我能做到这一点静态地以这种方式:

Now i've tried to order all by the first and second column. I could do it statically in this way:

someValues = someValues
    .OrderBy(t => t[0])
    .ThenBy(t => t[1])
    .ToList();

但是,如果我不知道列的数目我可以用这个循环(这是我的想法):

But if i don't know the number of "columns" i could use this loop(that's what I thought):

int minDim = someValues.Min(t => t.GetLength(0));  // 2
IOrderedEnumerable<string[]> orderedValues = someValues.OrderBy(t => t[0]);
for (int i = 1; i < minDim; i++)
{
    orderedValues = orderedValues.ThenBy(t => t[i]);
}
someValues = orderedValues.ToList();  // IndexOutOfRangeException 

但是,这并不工作,它无法与 IndexOutOfRangeException 在最后一行。调试器告诉我, 2 在那个时候,所以for循环的条件似乎被忽略, == minDim

But that doesn't work, it fails with an IndexOutOfRangeException at the last line. The debugger tells me that i is 2 at that time, so the for-loop condition seems to be ignored, i is already == minDim.

为什么会这样呢?什么是正确的途径呢?

Why is that so? What is the correct way for this?

推荐答案

这是同样的问题,因为很多人曾与的foreach 回路pre C#5

It's the same problem as lots of people had with foreach loops pre C# 5.

orderedValues = orderedValues.ThenBy(t => t[i]);

将不会被直到你调用评估 .ToList()此时它的值是2因为这是的退出条件的循环。

The value of i will not be evaluated until you call .ToList() at which point it is 2 since that's the exit condition of the for loop.

您可以引入一个新的局部变量的for循环的内部来解决它:

You can introduce a new local variable inside the for-loop to fix it:

for (int i = 1; i < minDim; i++)
{
    var tmp = i;
    orderedValues = orderedValues.ThenBy(t => t[tmp]);
}


有关更多信息,你可以看看关于<一个埃里克利珀的博客文章href="http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx"相对=nofollow>关闭了被认为是有害循环变量。


For more information you could take a look at Eric Lippert's blog post about Closing over the loop variable considered harmful.

这篇关于对于环和LINQ的延迟执行不玩好起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆