首页 文章

IEnumerable没有Count方法

提问于
浏览
69

我有以下方法:

public bool IsValid
{
  get { return (GetRuleViolations().Count() == 0); }
}

public IEnumerable<RuleViolation> GetRuleViolations(){
  //code here
}

为什么当我在上面做 .Count() 时,它用红色加下划线?

我收到以下错误:

错误1'System.Collections.Generic.IEnumerable'不包含'Count'的定义,并且没有扩展方法'Count'接受类型'System.Collections.Generic.IEnumerable'的第一个参数可以找到(你错过了吗?) using指令或程序集引用?)c:\ users \ a \ documents \ visual studio 2010 \ Projects \ NerdDinner \ NerdDinner \ Models \ Dinner.cs 15 47 NerdDinner

4 回答

  • 0

    IEnumeration 没有名为 Count() 的方法 . 这只是一种"sequence of elements" . 如果明确需要元素数,请使用例如 List . 如果您使用Linq请记住,扩展方法 Count() 实际上可能会在每次调用时重新计算元素数量 .

  • 141

    你添加:

    using System.Linq;
    

    在源代码的顶部,并确保您有一个System.Core程序集的引用 .

    Count()是LINQ to Objects的System.Linq.Enumerable静态类提供的扩展方法,LINQ to SQL和其他进程外提供程序的System.Linq.Queryable .

    编辑:事实上,在这里使用 Count() 是相对低效的(至少在LINQ to Objects中) . 所有你想知道的是否有任何元素,对吧?在这种情况下, Any() 更适合:

    public bool IsValid
    {
      get { return !GetRuleViolations().Any(); }
    }
    
  • 2

    Linq中的 Any()Count() 方法仅适用于泛型类型 .

    IEnumerable<T>
    

    如果你有一个没有类型的简单 IEnumerable ,请尝试使用

    IEnumerable<object>
    

    代替 .

  • 1

    怎么样:

    public bool IsValid
    {
        get { return (GetRuleViolations().Cast<RuleViolation>().Count() == 0); }
    }
    

相关问题