Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# linq increment variable inside anonymous select

Tags:

c#

linq

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?

like image 910
user3857731 Avatar asked Mar 09 '26 05:03

user3857731


2 Answers

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

like image 197
Marc Gravell Avatar answered Mar 11 '26 19:03

Marc Gravell


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

like image 30
Michael Mairegger Avatar answered Mar 11 '26 19:03

Michael Mairegger