user3857731
user3857731

Reputation: 659

C# linq increment variable inside anonymous select

In linq is it posible to increment variable inside anonymous select?

For example this is my code :

   int[] coefficients = { 1, 2, 3, };
   int i = 0;

   var verbalResult =
                  from fq in finishedQuizzes
                  from vq in fq.Quiz.VerbalQuizes
                  group vq by vq.Question.ExamTagId into r
                  select new
                  {
                      Tag = r.First().Question.ExamTag.Name,                 
                      CorrectAnswerCount = r.Sum(e => e.ISMovedAnswerCorrect ? 1 : 0),
                      questionCount = r.Count(),
                      coefficient = coefficients[i],
                      i++
                  };

I want to get coefficient by index(i). Can I increment the i variable like this?

Upvotes: 2

Views: 5182

Answers (2)

Michael Mairegger
Michael Mairegger

Reputation: 7301

No this is not possible. But there exists two solutions. Either you increment i in the indexer.

[...]
coefficient = coefficients[i++],
[...]

or you use the indexer:

var verbalResult = .... into r select r;
var result = verbalResult.Select((item,index) =>{ new { Tag = ... } /* index is the current position */}

Be aware of IndexOutOfRangeException when i or index exceeds coefficients.Length

Upvotes: 4

Marc Gravell
Marc Gravell

Reputation: 1063338

There are times when LINQ (the language bits) aren't as helpful as the actual library methods available. If you stick to the extension methods, there is an overload of Select that hands you the index. So... everything you want.

Basically:

.Select((x, i) => {...})

https://msdn.microsoft.com/en-us/library/bb534869(v=vs.100).aspx

Upvotes: 8

Related Questions