IEnumerable doesn't have a Count method

后端 未结 4 519
一整个雨季
一整个雨季 2020-11-27 19:06

I have the following method:

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

public IEnumerable GetRuleVio         


        
相关标签:
4条回答
  • 2020-11-27 19:09

    Any() or Count() methods in Linq work only for generic types.

    IEnumerable<T>
    

    If you have a simple IEnumerable without a type, try to use

    IEnumerable<object> 
    

    instead.

    0 讨论(0)
  • 2020-11-27 19:10

    How about:

    public bool IsValid
    {
        get { return (GetRuleViolations().Cast<RuleViolation>().Count() == 0); }
    }
    
    0 讨论(0)
  • 2020-11-27 19:20

    IEnumeration does not have a method called Count(). It's just a kind of "sequence of elements". Use for example List if you explicitly need the number of elements. If you use Linq keep in mind, that the extension method Count() may actually re-count the number of elements each time you call it.

    0 讨论(0)
  • 2020-11-27 19:24

    You add:

    using System.Linq;
    

    at the top of your source and make sure you've got a reference to the System.Core assembly.

    Count() is an extension method provided by the System.Linq.Enumerable static class for LINQ to Objects, and System.Linq.Queryable for LINQ to SQL and other out-of-process providers.

    EDIT: In fact, using Count() here is relatively inefficient (at least in LINQ to Objects). All you want to know is whether there are any elements or not, right? In that case, Any() is a better fit:

    public bool IsValid
    {
      get { return !GetRuleViolations().Any(); }
    }
    
    0 讨论(0)
提交回复
热议问题