gpt4 book ai didi

c# - 如何访问 IQueryable 对象中的连续元素?

转载 作者:行者123 更新时间:2023-11-30 13:43:11 25 4
gpt4 key购买 nike

我需要访问 IQueryable 对象中的当前元素和上一个元素。如果我有一个 int 数组,我会执行以下操作:

var array = new int[]{0,1,2,3,4};
for(var i = 1; i<array.Length ; i++)
{
method1(array[i-1], array[i]);
}

我不知道对 IQueryable 做同样的事情,因为它没有实现 IList。

最佳答案

使用扩展方法使这变得相当容易。

public static class IEnumerableExtensions
{
public static IEnumerable<ValueWithPrevious<T>> WithPrevious<T>(this IEnumerable<T> @this)
{
using (var e = @this.GetEnumerator())
{
if (!e.MoveNext())
yield break;

var previous = e.Current;

while (e.MoveNext())
{
yield return new ValueWithPrevious<T>(e.Current, previous);
previous = e.Current;
}
}
}
}

public struct ValueWithPrevious<T>
{
public readonly T Value, Previous;

public ValueWithPrevious(T value, T previous)
{
Value = value;
Previous = previous;
}
}

用法:

var array = new int[] { 1, 2, 3, 4, 5 };
foreach (var value in array.WithPrevious())
{
Console.WriteLine("{0}, {1}", value.Previous, value.Value);
// Results: 1, 2
// 2, 3
// 3, 4
// 4, 5
}

关于c# - 如何访问 IQueryable<T> 对象中的连续元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/709885/

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