编程语言
首页 > 编程语言> > c# – 如何访问IQueryable对象中的连续元素?

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

作者:互联网

我需要访问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,iteration,net,linq,iqueryable
来源: https://codeday.me/bug/20190722/1499423.html