这个问题已经在这里有一个答案:
我觉得有一些愚蠢的语法错误怎么回事,但我不能为我的生命数字出来。我想使用排序多个属性的大名单。
方法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是返回一个超出范围的错误。
嘿,这里的循环经典问题。正确的方法做到这一点:
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);