Return array index from a lambda but throws IndexOutOfRangeException












2















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.










share|improve this question

























  • Do you understand what the "IndexOutOfRange" execption indicates? It means that the i used in nums[i] is not a valid index for the num array. Ask yourself this: What is the range of valid indexes for your num array?

    – elgonzo
    Nov 25 '18 at 17:48













  • Yes of course. in this case for 2 should be 0. Is it out?

    – imanonami
    Nov 25 '18 at 17:49











  • Look up the documentation for Where. It does not do what you think it does... (docs.microsoft.com/en-gb/dotnet/api/…)

    – elgonzo
    Nov 25 '18 at 17:50













  • But shouldn't the "i" evaluates to 0?

    – imanonami
    Nov 25 '18 at 17:51











  • Again, look up the documentation to know what it does. Do not insist on wild blind guessing...

    – elgonzo
    Nov 25 '18 at 17:52


















2















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.










share|improve this question

























  • Do you understand what the "IndexOutOfRange" execption indicates? It means that the i used in nums[i] is not a valid index for the num array. Ask yourself this: What is the range of valid indexes for your num array?

    – elgonzo
    Nov 25 '18 at 17:48













  • Yes of course. in this case for 2 should be 0. Is it out?

    – imanonami
    Nov 25 '18 at 17:49











  • Look up the documentation for Where. It does not do what you think it does... (docs.microsoft.com/en-gb/dotnet/api/…)

    – elgonzo
    Nov 25 '18 at 17:50













  • But shouldn't the "i" evaluates to 0?

    – imanonami
    Nov 25 '18 at 17:51











  • Again, look up the documentation to know what it does. Do not insist on wild blind guessing...

    – elgonzo
    Nov 25 '18 at 17:52
















2












2








2








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.










share|improve this question
















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.







c# linq lambda return indexoutofboundsexception






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 18:14









egor.zhdan

3,53053348




3,53053348










asked Nov 25 '18 at 17:39









imanonamiimanonami

132




132













  • Do you understand what the "IndexOutOfRange" execption indicates? It means that the i used in nums[i] is not a valid index for the num array. Ask yourself this: What is the range of valid indexes for your num array?

    – elgonzo
    Nov 25 '18 at 17:48













  • Yes of course. in this case for 2 should be 0. Is it out?

    – imanonami
    Nov 25 '18 at 17:49











  • Look up the documentation for Where. It does not do what you think it does... (docs.microsoft.com/en-gb/dotnet/api/…)

    – elgonzo
    Nov 25 '18 at 17:50













  • But shouldn't the "i" evaluates to 0?

    – imanonami
    Nov 25 '18 at 17:51











  • Again, look up the documentation to know what it does. Do not insist on wild blind guessing...

    – elgonzo
    Nov 25 '18 at 17:52





















  • Do you understand what the "IndexOutOfRange" execption indicates? It means that the i used in nums[i] is not a valid index for the num array. Ask yourself this: What is the range of valid indexes for your num array?

    – elgonzo
    Nov 25 '18 at 17:48













  • Yes of course. in this case for 2 should be 0. Is it out?

    – imanonami
    Nov 25 '18 at 17:49











  • Look up the documentation for Where. It does not do what you think it does... (docs.microsoft.com/en-gb/dotnet/api/…)

    – elgonzo
    Nov 25 '18 at 17:50













  • But shouldn't the "i" evaluates to 0?

    – imanonami
    Nov 25 '18 at 17:51











  • Again, look up the documentation to know what it does. Do not insist on wild blind guessing...

    – elgonzo
    Nov 25 '18 at 17:52



















Do you understand what the "IndexOutOfRange" execption indicates? It means that the i used in nums[i] is not a valid index for the num array. Ask yourself this: What is the range of valid indexes for your num array?

– elgonzo
Nov 25 '18 at 17:48







Do you understand what the "IndexOutOfRange" execption indicates? It means that the i used in nums[i] is not a valid index for the num array. Ask yourself this: What is the range of valid indexes for your num array?

– elgonzo
Nov 25 '18 at 17:48















Yes of course. in this case for 2 should be 0. Is it out?

– imanonami
Nov 25 '18 at 17:49





Yes of course. in this case for 2 should be 0. Is it out?

– imanonami
Nov 25 '18 at 17:49













Look up the documentation for Where. It does not do what you think it does... (docs.microsoft.com/en-gb/dotnet/api/…)

– elgonzo
Nov 25 '18 at 17:50







Look up the documentation for Where. It does not do what you think it does... (docs.microsoft.com/en-gb/dotnet/api/…)

– elgonzo
Nov 25 '18 at 17:50















But shouldn't the "i" evaluates to 0?

– imanonami
Nov 25 '18 at 17:51





But shouldn't the "i" evaluates to 0?

– imanonami
Nov 25 '18 at 17:51













Again, look up the documentation to know what it does. Do not insist on wild blind guessing...

– elgonzo
Nov 25 '18 at 17:52







Again, look up the documentation to know what it does. Do not insist on wild blind guessing...

– elgonzo
Nov 25 '18 at 17:52














2 Answers
2






active

oldest

votes


















0














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;





share|improve this answer


























  • Great Akhkan, could you explain how your Linq works? I mean how for other indexes it work?

    – imanonami
    Nov 25 '18 at 18:13













  • @Ashkan you need to add a condition to .FirstOrDefault(n => n.x == 2). Otherwise, you just get the first element.

    – Dmitry Stepanov
    Nov 25 '18 at 18:16













  • in (x,i), x is the item itself and i is the index, so the Select would return: [{x =2, i =0}, {x=3, i= 1}, {x=5, i=2}, ...], so FirstOrDefault(a => a.x == 2)` would mean the item from our new collection where it's x value is 2, and after finding its i property would be the index. but it is much slower than indexof, so i reccomand using indexof.

    – Ashkan Mobayen Khiabani
    Nov 25 '18 at 18:18











  • @DmitryS Thank you, your suggestion works!

    – imanonami
    Nov 25 '18 at 18:20













  • @AshkanMobayenKhiabani Great, I just need to learn for future use of Linq and Lambda

    – imanonami
    Nov 25 '18 at 18:24



















0














i in your lambda is an element (and not the index) of the nums array.



So, first i is equal to 2 (the first element of nums). nums[2] != 2, so it goes further.



i is equal to 3 (the second element of nums). nums[3] != 2, so it goes further.



Then, i is equal to 5 (the third element of nums).nums[5] != 2 but your array has 5 elements and the last element has index 4 (because index is zero based). So, when you tried to access nums[5] you get an IndexOutOfRangeException expectedly.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53470138%2freturn-array-index-from-a-lambda-but-throws-indexoutofrangeexception%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    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;





    share|improve this answer


























    • Great Akhkan, could you explain how your Linq works? I mean how for other indexes it work?

      – imanonami
      Nov 25 '18 at 18:13













    • @Ashkan you need to add a condition to .FirstOrDefault(n => n.x == 2). Otherwise, you just get the first element.

      – Dmitry Stepanov
      Nov 25 '18 at 18:16













    • in (x,i), x is the item itself and i is the index, so the Select would return: [{x =2, i =0}, {x=3, i= 1}, {x=5, i=2}, ...], so FirstOrDefault(a => a.x == 2)` would mean the item from our new collection where it's x value is 2, and after finding its i property would be the index. but it is much slower than indexof, so i reccomand using indexof.

      – Ashkan Mobayen Khiabani
      Nov 25 '18 at 18:18











    • @DmitryS Thank you, your suggestion works!

      – imanonami
      Nov 25 '18 at 18:20













    • @AshkanMobayenKhiabani Great, I just need to learn for future use of Linq and Lambda

      – imanonami
      Nov 25 '18 at 18:24
















    0














    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;





    share|improve this answer


























    • Great Akhkan, could you explain how your Linq works? I mean how for other indexes it work?

      – imanonami
      Nov 25 '18 at 18:13













    • @Ashkan you need to add a condition to .FirstOrDefault(n => n.x == 2). Otherwise, you just get the first element.

      – Dmitry Stepanov
      Nov 25 '18 at 18:16













    • in (x,i), x is the item itself and i is the index, so the Select would return: [{x =2, i =0}, {x=3, i= 1}, {x=5, i=2}, ...], so FirstOrDefault(a => a.x == 2)` would mean the item from our new collection where it's x value is 2, and after finding its i property would be the index. but it is much slower than indexof, so i reccomand using indexof.

      – Ashkan Mobayen Khiabani
      Nov 25 '18 at 18:18











    • @DmitryS Thank you, your suggestion works!

      – imanonami
      Nov 25 '18 at 18:20













    • @AshkanMobayenKhiabani Great, I just need to learn for future use of Linq and Lambda

      – imanonami
      Nov 25 '18 at 18:24














    0












    0








    0







    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;





    share|improve this answer















    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;






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 25 '18 at 18:16

























    answered Nov 25 '18 at 18:02









    Ashkan Mobayen KhiabaniAshkan Mobayen Khiabani

    20.9k1667119




    20.9k1667119













    • Great Akhkan, could you explain how your Linq works? I mean how for other indexes it work?

      – imanonami
      Nov 25 '18 at 18:13













    • @Ashkan you need to add a condition to .FirstOrDefault(n => n.x == 2). Otherwise, you just get the first element.

      – Dmitry Stepanov
      Nov 25 '18 at 18:16













    • in (x,i), x is the item itself and i is the index, so the Select would return: [{x =2, i =0}, {x=3, i= 1}, {x=5, i=2}, ...], so FirstOrDefault(a => a.x == 2)` would mean the item from our new collection where it's x value is 2, and after finding its i property would be the index. but it is much slower than indexof, so i reccomand using indexof.

      – Ashkan Mobayen Khiabani
      Nov 25 '18 at 18:18











    • @DmitryS Thank you, your suggestion works!

      – imanonami
      Nov 25 '18 at 18:20













    • @AshkanMobayenKhiabani Great, I just need to learn for future use of Linq and Lambda

      – imanonami
      Nov 25 '18 at 18:24



















    • Great Akhkan, could you explain how your Linq works? I mean how for other indexes it work?

      – imanonami
      Nov 25 '18 at 18:13













    • @Ashkan you need to add a condition to .FirstOrDefault(n => n.x == 2). Otherwise, you just get the first element.

      – Dmitry Stepanov
      Nov 25 '18 at 18:16













    • in (x,i), x is the item itself and i is the index, so the Select would return: [{x =2, i =0}, {x=3, i= 1}, {x=5, i=2}, ...], so FirstOrDefault(a => a.x == 2)` would mean the item from our new collection where it's x value is 2, and after finding its i property would be the index. but it is much slower than indexof, so i reccomand using indexof.

      – Ashkan Mobayen Khiabani
      Nov 25 '18 at 18:18











    • @DmitryS Thank you, your suggestion works!

      – imanonami
      Nov 25 '18 at 18:20













    • @AshkanMobayenKhiabani Great, I just need to learn for future use of Linq and Lambda

      – imanonami
      Nov 25 '18 at 18:24

















    Great Akhkan, could you explain how your Linq works? I mean how for other indexes it work?

    – imanonami
    Nov 25 '18 at 18:13







    Great Akhkan, could you explain how your Linq works? I mean how for other indexes it work?

    – imanonami
    Nov 25 '18 at 18:13















    @Ashkan you need to add a condition to .FirstOrDefault(n => n.x == 2). Otherwise, you just get the first element.

    – Dmitry Stepanov
    Nov 25 '18 at 18:16







    @Ashkan you need to add a condition to .FirstOrDefault(n => n.x == 2). Otherwise, you just get the first element.

    – Dmitry Stepanov
    Nov 25 '18 at 18:16















    in (x,i), x is the item itself and i is the index, so the Select would return: [{x =2, i =0}, {x=3, i= 1}, {x=5, i=2}, ...], so FirstOrDefault(a => a.x == 2)` would mean the item from our new collection where it's x value is 2, and after finding its i property would be the index. but it is much slower than indexof, so i reccomand using indexof.

    – Ashkan Mobayen Khiabani
    Nov 25 '18 at 18:18





    in (x,i), x is the item itself and i is the index, so the Select would return: [{x =2, i =0}, {x=3, i= 1}, {x=5, i=2}, ...], so FirstOrDefault(a => a.x == 2)` would mean the item from our new collection where it's x value is 2, and after finding its i property would be the index. but it is much slower than indexof, so i reccomand using indexof.

    – Ashkan Mobayen Khiabani
    Nov 25 '18 at 18:18













    @DmitryS Thank you, your suggestion works!

    – imanonami
    Nov 25 '18 at 18:20







    @DmitryS Thank you, your suggestion works!

    – imanonami
    Nov 25 '18 at 18:20















    @AshkanMobayenKhiabani Great, I just need to learn for future use of Linq and Lambda

    – imanonami
    Nov 25 '18 at 18:24





    @AshkanMobayenKhiabani Great, I just need to learn for future use of Linq and Lambda

    – imanonami
    Nov 25 '18 at 18:24













    0














    i in your lambda is an element (and not the index) of the nums array.



    So, first i is equal to 2 (the first element of nums). nums[2] != 2, so it goes further.



    i is equal to 3 (the second element of nums). nums[3] != 2, so it goes further.



    Then, i is equal to 5 (the third element of nums).nums[5] != 2 but your array has 5 elements and the last element has index 4 (because index is zero based). So, when you tried to access nums[5] you get an IndexOutOfRangeException expectedly.






    share|improve this answer






























      0














      i in your lambda is an element (and not the index) of the nums array.



      So, first i is equal to 2 (the first element of nums). nums[2] != 2, so it goes further.



      i is equal to 3 (the second element of nums). nums[3] != 2, so it goes further.



      Then, i is equal to 5 (the third element of nums).nums[5] != 2 but your array has 5 elements and the last element has index 4 (because index is zero based). So, when you tried to access nums[5] you get an IndexOutOfRangeException expectedly.






      share|improve this answer




























        0












        0








        0







        i in your lambda is an element (and not the index) of the nums array.



        So, first i is equal to 2 (the first element of nums). nums[2] != 2, so it goes further.



        i is equal to 3 (the second element of nums). nums[3] != 2, so it goes further.



        Then, i is equal to 5 (the third element of nums).nums[5] != 2 but your array has 5 elements and the last element has index 4 (because index is zero based). So, when you tried to access nums[5] you get an IndexOutOfRangeException expectedly.






        share|improve this answer















        i in your lambda is an element (and not the index) of the nums array.



        So, first i is equal to 2 (the first element of nums). nums[2] != 2, so it goes further.



        i is equal to 3 (the second element of nums). nums[3] != 2, so it goes further.



        Then, i is equal to 5 (the third element of nums).nums[5] != 2 but your array has 5 elements and the last element has index 4 (because index is zero based). So, when you tried to access nums[5] you get an IndexOutOfRangeException expectedly.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 25 '18 at 18:01

























        answered Nov 25 '18 at 17:51









        Dmitry StepanovDmitry Stepanov

        1,1491123




        1,1491123






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53470138%2freturn-array-index-from-a-lambda-but-throws-indexoutofrangeexception%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            To store a contact into the json file from server.js file using a class in NodeJS

            Marschland

            Redirect URL with Chrome Remote Debugging Android Devices