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?
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
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
iorindexexceedscoefficients.Length
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With