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

2024-04-30

我有一个嵌套列表,

List<List<String>> intable;

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

像这样对列表进行排序效果很好(假设本例有 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();

但是,当我将其放入循环中时,如下所示:

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

它不再正常工作,并且仅对第四列进行排序。


这是一个案例访问修改后的闭包。将代码更改为这样,它将起作用:

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)写了一篇两部分文章 http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx描述问题。简而言之,它没有按您期望的方式工作的原因是因为 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

OrderBy / ThenBy 循环 - C# 中的嵌套列表 的相关文章

随机推荐