c# - C# 中的 LINQ 查询和子查询枚举计数?

标签 c# .net linq .net-4.0

假设我有这个查询:

  int[] Numbers= new int[5]{5,2,3,4,5};

  var query =  from a in Numbers
      where a== Numbers.Max (n => n) //notice MAX  he should also get his value somehow
      select a;

foreach (var element in query)
  Console.WriteLine (element);
  • Numbers 在运行 foreach 时被枚举多少次?

  • 我如何测试它(我的意思是,编写一个告诉我迭代次数的代码)

最佳答案

会迭代6次。一次用于 Where,一次用于 Max

演示代码:

private static int count = 0;
public static IEnumerable<int> Regurgitate(IEnumerable<int> source)
{
    count++;
    Console.WriteLine("Iterated sequence {0} times", count);
    foreach (int i in source)
        yield return i;
}

int[] Numbers = new int[5] { 5, 2, 3, 4, 5 };

IEnumerable<int> sequence = Regurgitate(Numbers);

var query = from a in sequence
            where a == sequence.Max(n => n)
            select a;

它将打印“Iterated sequence 6 times”。

如果您打算用它来试验其他情况,我们可以制作一个更通用、更灵活的包装器:

public class EnumerableWrapper<T> : IEnumerable<T>
{
    private IEnumerable<T> source;
    public EnumerableWrapper(IEnumerable<T> source)
    {
        this.source = source;
    }

    public int IterationsStarted { get; private set; }
    public int NumMoveNexts { get; private set; }
    public int IterationsFinished { get; private set; }

    public IEnumerator<T> GetEnumerator()
    {
        IterationsStarted++;

        foreach (T item in source)
        {
            NumMoveNexts++;
            yield return item;
        }

        IterationsFinished++;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public override string ToString()
    {
        return string.Format(
@"Iterations Started: {0}
Iterations Finished: {1}
Number of move next calls: {2}"
, IterationsStarted, IterationsFinished, NumMoveNexts);

    }
}

与其他函数相比,这有几个优点:

  1. 它记录开始的迭代次数、完成的迭代次数以及所有序列递增的总次数。
  2. 您可以创建不同的实例来包装不同的底层序列,从而允许您检查每个程序的多个序列,而不是使用静态变量时只检查一个序列。

关于c# - C# 中的 LINQ 查询和子查询枚举计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13706316/

相关文章:

c# - 有没有办法在不关闭 StreamWriter 的情况下关闭其 BaseStream?

c# - 异步 HttpHandler 的请求是否可以无异常地中断?

.net - 如何通过代码阅读所有共享的谷歌阅读器提要?

c# - 在带有复选框的GridView中显示存储过程的结果

c# - OrderBy 的特例

c# - Linq 两个 select 语句,第二个使用第一个结果,

c# - Windows Media Player Control (winforms) - 将当前帧捕获为位图?

C# 生成查询以将 DateTime 与 SQL Nvarchar 日期列进行比较

c# - 如何将智能标记添加到我的 .NET 组件?

c# - Linq Group 结果到对象