Change value of each element by linq

Is it possible to do sth like this in LINQ:

int[] d = new int[c.Length + 1];     
int e = 1;
                d.ToList().ForEach(r => 
                {
                    r = e;
                    e++;
                });

?. When I did this, it returned me sequence of zeros. Regards.

Jon Skeet
people
quotationmark

Yes, it would, for two reasons:

  • You're creating a copy of the original array as a List<int>, and then trying to modify the List<int>. That wouldn't modify the array.
  • Your lambda expression changes the value of the parameter, that's all. It doesn't modify the list.

Basically, LINQ is for querying. Don't even bother trying to do this: use a for loop if you want to modify the collection.

However, if your aim is to produce an array of 1...(c.Length+1), just use Enumerable.Range:

var array = Enumerable.Range(1, c.Length + 1).ToArray();

people

See more on this question at Stackoverflow