优化LINQ Count()> X

时间:2016-11-02 13:01:32

标签: c# linq

问题:给定IEnumerable<>,如何检查哪些序列包含的内容多于x项?

MCVE

static void Main(string[] args)
{
    var test = Test().Where(o => o > 2 && o < 6); // ToList()
    if (test.Count() > 1) // how to optimize this?
        foreach (var t in test) // consumer
            Console.WriteLine(t);
}

static IEnumerable<int> Test()
{
    for (int i = 0; i < 10; i++)
        yield return i;
}

这里的问题是Count()将运行完整序列,而1E6 +项目(ToList()也是错误的想法)。我也不被允许更改消费者代码(这是一种接受完整序列的方法)。

1 个答案:

答案 0 :(得分:18)

如果 test集合(当Count() 昂贵时),您可以尝试一个典型的技巧:

if (test.Skip(1).Any()) 

一般情况下 test.Count() > x可以重写为

if (test.Skip(x).Any()) 

修改:你可能希望在方法隐藏这样的技巧,比如EnsureCount

  public static partial class EnumerableExtensions {
    public static IEnumerable<T> EnsureCount<T>(this IEnumerable<T> source, int count) {
      if (null == source)
        throw new ArgumentNullException("source");

      if (count <= 0)
        foreach (var item in source)
          yield return item;
      else {
        List<T> buffer = new List<T>(count);

        foreach (var item in source) {
          if (buffer == null)
            yield return item;
          else {
            buffer.Add(item);

            if (buffer.Count >= count) {
              foreach (var x in buffer)
                yield return x;

              buffer = null;
            }
          }
        }
      }
    }
  } 

所以你的代码将是

  var test = Test()
    .Where(o => o > 2 && o < 6)
    .EnsureCount(2); // <- Count() > 1, so at least 2 items

  foreach (var t in test)
    Console.WriteLine(t); 
相关问题