有麻烦的环路内执行LINQ的ThenBy [复制]

问题描述 投票:-1回答:1

这个问题已经在这里有一个答案:

我觉得有一些愚蠢的语法错误怎么回事,但我不能为我的生命数字出来。我想使用排序多个属性的大名单。

方法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);

上述方法的作品完美,但方法B(我需要做的方式)保持返回一个索引超出范围的错误,即使它应该是完全相同的(即0,1,2)

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

c# linq linq-to-entities
1个回答
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#

© www.soinside.com 2019 - 2024. All rights reserved.