2

When I execute it, it stops printing at 8 and shows me

"System.ArgumentOutOfRangeException"

List<int> number = new List<int> { 1, 2, 2, 5, 4, 8, 6};
number.ForEach(delegate (int i) { Console.WriteLine(number[i]); });
Console.ReadKey();
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • 6
    ForEach passes you the __value__, not the __index__. – tkausl Apr 02 '20 at 11:17
  • FYI you can also use lambdas to make it shorter `number.ForEach(x => Console.WriteLine(x));` – juharr Apr 02 '20 at 11:21
  • "it stops printing at 8" yes it should.. and it gives a range exception, because your array is 7 elements 0..6 and your number[5]=8, so number[number[5]] is out range. The tkausl comment is right: your LINQ returns the values of your array, not the index. – Goodies Apr 02 '20 at 11:28
  • Do you need the index? If you do and you really don't want to have a classic For loop or a foreach with a counter, there is a 3rd way using a select to get the value and the index [demo](https://dotnetfiddle.net/vEY26Z) – Drag and Drop Apr 02 '20 at 11:47
  • Can you link me something that shows how its done? Or if possible show me, that would be great. – Mohammed Daoudi Apr 02 '20 at 12:48

2 Answers2

3

As @tkausl already mentioned, ForEach passes you the value, not the index, it is not recommended to use List.ForEach actually, but if you still want to use it, you can do something like this:

 number.ForEach(c => { Console.WriteLine(c); });

You can simply use a foreach like this:

foreach (var c in number)
{
   Console.WriteLine(c);
}

You can find the discussion here: foreach vs someList.ForEach(){}

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
2

You can use this foreach , It will never make a mistake

List<int> number = new List<int> { 1, 2, 2, 5, 4, 8, 6 };
foreach (var item in number)
{
    Console.WriteLine(item);
}
Stefan
  • 17,448
  • 11
  • 60
  • 79
Soheila Tarighi
  • 487
  • 4
  • 15