-1

Can we update external variable through linq, i.e., can we update a variable which is not being used in linq's scope through a linq?

For example, this is what I tried:

var s = list_UIModes_And_Related_Actions_Details
  .Select(x => x.ActionIdList)
  .Select(y => modeAndActionRelationTable[Counter++] = Convert.ToByte(y));

But this line doesn't update modeAndActionRelationTable array.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Vaishali
  • 131
  • 9

1 Answers1

4

Yes, you can change any variable inside your LINQ statement, but you should refrain from doing so.

In your example, if you walk over the enumerable s twice, Counter will go out of bounds. If it iterates only half way, and starts over, Counter will be off too. It is just not reliable.

Your code will probably work the first time you materialize the enumerable entirely. Adding ToList() or ToArray() will do that for you.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325