0

I feel like there is some silly syntax error going on here but I can't for the life of me figure it out. I am trying to sort a big list using multiple properties.

Method 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);

Method 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);

The above Method A works perfectly, but Method B (the way I need to do it) keeps returning an index out of range error, even though it should be the exact same (i.e. 0, 1, 2)

In both instances e.Priority represents a list of 3 KeyValuePairs. I don't understand why Method B is returning an out of range error.

aadu
  • 3,196
  • 9
  • 39
  • 62
  • not sure this deserves a -1, yes it's a duplicate but it's a well structured question and there was no way for me to know it was a duplicate – aadu Feb 12 '19 at 16:31
  • I agree; this is a tricky problem I ran into myself, and it was not clear that the solution was to "capture within a loop". As such, I probably would never have found that question without this one. – Taylor May 28 '20 at 23:27

1 Answers1

0

Heh, classic problem of loops here. Correct way to do it:

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

More here: Captured variable in a loop in C#

eocron
  • 6,885
  • 1
  • 21
  • 50
  • Aha, today I have learned something new. Crazy I have not encountered this problem before. Maybe because I don't use LINQ very often. – aadu Feb 11 '19 at 16:34
  • This problem often occurs when you use Lamda in cycles (for, foreach, while). Regardlles if it is LINQ or something else. – eocron Feb 11 '19 at 16:38
  • Ah, it was the Lamda. This must be the first time I've tried to use one in a loop – aadu Feb 11 '19 at 16:43