gpt4 book ai didi

c# - 从 lambda 返回数组索引但抛出 IndexOutOfRangeException

转载 作者:太空宇宙 更新时间:2023-11-03 14:47:40 25 4
gpt4 key购买 nike

我正在尝试学习如何使用 lambda,在这段代码中,我正在尝试获取数组中可用的某个值的索引,但它只返回值 5 和 8 正常,而对于其他值它不断抛出 IndexOutOfRangeException!

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

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

请告诉我在尝试检索“索引”返回值时会发生什么情况?提前致谢。

最佳答案

在你的 lambda 表达式 (i => nums[i] == 2) 中,i 将代表数字本身而不是它的索引所以 nums[i ] 将不起作用。

您可以使用 Array.IndexOf() 简单地执行此操作:

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

或者如果你坚持用 Linq 来做(不推荐):

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

关于c# - 从 lambda 返回数组索引但抛出 IndexOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53470138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com