Search code examples
c#linqlambdareturnindexoutofboundsexception

Return array index from a lambda but throws IndexOutOfRangeException


I'm trying to learn how to use lambdas and in this code I'm trying to get index of some value that is available in the array, but it just return for values 5 and 8 fine and for the other values it keeps throwing IndexOutOfRangeException!

int[] nums = { 2, 3, 5, 8, 9 };

int rez = nums.Where(i => nums[i] == 2).FirstOrDefault();
Console.WriteLine(rez);

Please tell me what would happen to "index" return value while trying to retrieving it? Thanks in advance.


Solution

  • in your lambda expression (i => nums[i] == 2), i would represent the number itself not its index so nums[i] won't work.

    You can simply do this using Array.IndexOf():

    int rez =  Array.IndexOf(nums, 2);
    

    Or if you insist on doing it by Linq (not recommended):

    int rez = nums.Select((x, i) => new {x, i}).FirstOrDefault(a => a.x == 2).i;