OrderBy/ThenBy循环-C#中的嵌套列表 [英] OrderBy / ThenBy looping - nested Lists in C#
问题描述
我有一个嵌套列表,
List<List<String>> intable;
我想对所有列进行排序.问题在于列数取决于用户输入.
where I would like to sort all the columns. The problem is that the number of columns depends on user input.
按这样对列表进行排序可以很好地工作(此示例假设4列)
Sorting the list like this works fine (assuming 4 columns for this example)
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();
但是,当我将其放入循环中时,就像这样:
But, when I put it in a loop, like this:
var tmp = intable.OrderBy(x => x[0]);
for (int i = 1; i <= 3; i++)
{
tmp = tmp.ThenBy(x => x[i]);
}
intable = tmp.ToList();
它不再正常工作,并且仅对第四列进行排序.
it no longer works correctly, and sorts only the fourth column.
推荐答案
这是访问修改后的闭包的情况.将代码更改为此,它将起作用:
This is a case of access to a modified closure. Change the code to this and it will work:
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();
Eric Lippert has written a two-part article describing the problem. The reason it doesn't work as you expect to is - in short - because LINQ is only using the last value of i
when it is evaluated when you call ToList()
. It's the same as if you had written:
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();
这篇关于OrderBy/ThenBy循环-C#中的嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!