c# - IEnumerable - 返回元素两侧范围内的项目

标签 c# linq ienumerable

我需要从 IEnumerable 中获取一个元素,然后返回它本身以及两侧的一系列元素。

所以,像这样:

var enumerable = new[] {54, 107, 24, 223, 134, 65, 36, 7342, 812, 96, 106};
var rangeSize = 2;
var range = enumerable.MySelectRange(x => x == 134, rangeSize);

会返回类似于 { 24, 223, 134, 65, 36 } 的内容.

(本项目使用.Net 3.5)

编辑 好的,人们似乎对整数数组很感兴趣。 我更改了示例,希望能更清楚地说明我所追求的目标。

请记住,这不一定适用于 IEnumerable<int> , 但实际上是一个 IEnumerable<TSomething> .

最佳答案

此扩展方法在序列中找到满足给定谓词的第一个元素,然后返回该元素及其一定数量的相邻元素。它处理最终情况。

public static IEnumerable<T> FirstAndNeighbours<T>(
  this IEnumerable<T> source,
  Func<T,bool> predicate,
  int numOfNeighboursEitherSide)
{
  using (var enumerator = source.GetEnumerator())
  {
    var precedingNeighbours = new Queue<T>(numOfNeighboursEitherSide);
    while(enumerator.MoveNext())
    {
      var current = enumerator.Current;
      if (predicate(current))
      {
        //We have found the first matching element. First, we must return
        //the preceding neighbours.
        foreach (var precedingNeighbour in precedingNeighbours)
          yield return precedingNeighbour;

        //Next, return the matching element.
        yield return current;

        //Finally, return the succeeding neighbours.
        for (int i = 0; i < numOfNeighboursEitherSide; ++i)
        {
          if (!enumerator.MoveNext())
            yield break;

          yield return enumerator.Current;
        }
        yield break;
      }
      //No match yet, keep track of this preceding neighbour.
      if (precedingNeighbours.Count >= numOfNeighboursEitherSide)
        precedingNeighbours.Dequeue();
      precedingNeighbours.Enqueue(current);
    }
  }
}

关于c# - IEnumerable - 返回元素两侧范围内的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7147198/

相关文章:

c# - 抛出 TimeoutException 是一个好的做法吗?

c# - 在 C# 中使用 RSA 加密和在 Java 中解密时出现填充错误

c# - 通过 IEnumerable 进行分页

c# - 将数组转换为 IEnumerable<T>

c# - 根据 .NET Core 2.1 中的更改重新加载 Serilog JSON 配置

c# - 在 foreach 循环中使用多个数据项

c# - 如何加快此 LINQ 查询的速度?

c# - Linq 从 Dictionary 值匹配中返回WhereEnumerableIterator?

c# - LINQ 扩展如何链接其他扩展

c# - 无限枚举仍然是 "enumerable"吗?