OrderBy/ThenBy循环 - C#中的嵌套列表

phi*_*hil 14 c# linq

我有一个嵌套列表,

List<List<String>> intable;
Run Code Online (Sandbox Code Playgroud)

在哪里我想对所有列进行排序.问题是列数取决于用户输入.

像这样排序列表工作正常(假设此示例为4列)

var tmp = intable.OrderBy(x => x[0]);
tmp = tmp.ThenBy(x => x[1]);
tmp = tmp.ThenBy(x => x[2]);
tmp = tmp.ThenBy(x => x[3]);
intable = tmp.ToList();
Run Code Online (Sandbox Code Playgroud)

但是,当我把它放在循环中时,像这样:

var tmp = intable.OrderBy(x => x[0]);
for (int i = 1; i <= 3; i++)
{
        tmp = tmp.ThenBy(x => x[i]);
}
intable = tmp.ToList();
Run Code Online (Sandbox Code Playgroud)

它不再正常工作,只排序第四列.

Yuc*_*uck 25

这是访问修改后的闭包的情况.将代码更改为此,它将工作:

var tmp = intable.OrderBy(x => x[0]);
for (int i = 1; i <= 3; i++) {
    var thisI = i;
    tmp = tmp.ThenBy(x => x[thisI]);
}
intable = tmp.ToList();
Run Code Online (Sandbox Code Playgroud)

Eric Lippert撰写了一篇两部分组成的文章,描述了这个问题.它无法按预期工作的原因 - 简而言之 - 因为LINQ仅使用i调用时评估的最后一个值ToList().这和你写的一样:

var tmp = intable.OrderBy(x => x[0]);
tmp = tmp.ThenBy(x => x[3]);
tmp = tmp.ThenBy(x => x[3]);
tmp = tmp.ThenBy(x => x[3]);
intable = tmp.ToList();
Run Code Online (Sandbox Code Playgroud)

  • @AdamSpicer:对于"for"循环,它不会改变,只是为了"foreach"循环. (6认同)
  • Eric Lippert确认在C#5中关闭行为会发生变化.[SO Link Here](http://stackoverflow.com/a/8899347/498969) (5认同)