views:

255

answers:

2

I have the following method:

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

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

Why is it that when I do .Count above it is underlined in red?

I got the following error:

Error 1 'System.Collections.Generic.IEnumerable' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?) c:\users\a\documents\visual studio 2010\Projects\NerdDinner\NerdDinner\Models\Dinner.cs 15 47 NerdDinner

+15  A: 

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(); }
}
Jon Skeet
If this reference gives you an error, verify that the Target Framework of your project (in the project properties, Application tab) is set to .NET Framework 3.5 or 4. Extension methods won't work on 2.0 or earlier.
willvv
I've had the using System.Linq; but it doesn't resolve my issue... how can I make sure that I got a reference to the System.Core assembly?
EquinoX
Target framework is .NET Framework 4
EquinoX
Oh nevermind, I fixed it... what is the different between System.data.linq and System.Linq
EquinoX
@Alexander: They're entirely different namespaces. `System.Data.Linq` is specific to LINQ to SQL.
Jon Skeet
Maybe it should be revised in the NerdDinner tutorial that I am using as it uses Count instead of Any
EquinoX
@Alexander: Quite possibly :)
Jon Skeet
+1  A: 

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.

Danvil