在循环内执行LINQ的ThenBy有麻烦

时间:2019-02-11 16:29:39

标签: c# linq linq-to-entities

我感觉这里发生了一些愚蠢的语法错误,但是我一生都无法解决。我正在尝试使用多个属性对一个大列表进行排序。

方法A:

IOrderedEnumerable<myClass> orderedList = myList.OrderByDescending(e => e.Tier);

orderedList = orderedList.ThenByDescending(e => e.Priority[0].Value);
orderedList = orderedList.ThenByDescending(e => e.Priority[1].Value);
orderedList = orderedList.ThenByDescending(e => e.Priority[2].Value);

orderedList = orderedList.ThenByDescending(e => e.Score);

方法B:

IOrderedEnumerable<myClass> orderedList = myList.OrderByDescending(e => e.Tier);

for (int i = 0; i < 3; i++)
{
    orderedList = orderedList.ThenByDescending(e => e.Priority[i].Value);
}

orderedList = orderedList.ThenByDescending(e => e.Score);

上述方法A可以完美地工作,但是方法B(我需要这样做)仍然返回超出范围错误的索引,即使它应该完全相同(即0、1、2)

在两种情况下,e.Priority代表3个KeyValuePair的列表。我不明白为什么方法B会返回超出范围的错误。

1 个答案:

答案 0 :(得分:0)

嘿,这里有经典的循环问题。正确的方法:

IOrderedEnumerable<myClass> orderedList = myList.OrderByDescending(e => e.Tier);

for (int i = 0; i < 3; i++)
{
    int capturedIndex = i;
    orderedList = orderedList.ThenByDescending(e => e.Priority[capturedIndex].Value);
}

orderedList = orderedList.ThenByDescending(e => e.Score);

更多内容:Captured variable in a loop in C#