gpt4 book ai didi

c# - 是否有返回索引的 Linq 函数?

转载 作者:行者123 更新时间:2023-12-02 13:50:14 25 4
gpt4 key购买 nike

基本上,相当于:

public static IEnumerable<KeyValuePair<int, T>> Enumerate<T>(this IEnumerable<T> enumerable)
{
int i = 0;
return enumerable.Select(e => new KeyValuePair<int, T>(i++, e));
}

Python 有一个,但我在 C# 中找不到它。如果没有,没什么大不了的,我只是写了它,但如果它已经存在,我宁愿坚持标准。避免在每个 foreach 上方添加一个笨拙的 int i=0 声明。

最佳答案

return enumerable.Select((e, i) => new KeyValuePair<int, T>(i, e));

另请注意,您使用 i++ 作为捕获变量的方法并不安全;例如,有人可以先调用 Count() - 使用 Parallel

关于c# - 是否有返回索引的 Linq 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4211558/

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