IEnumerable doesn't have a Count method
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(); }
}
How can I have the method Count() of IEnumerableDirectoryInfo?
Count<T>()
is an extension method for IEnumerable<T>
. To use it, you should add:
using System.Linq;
Extension Methods
The most common extension methods are the LINQ standard query
operators that add query functionality to the existing
System.Collections.IEnumerable
and
System.Collections.Generic.IEnumerable<T>
types.
To use the standard
query operators, first bring them into scope with ausing System.Linq
directive.
Then any type that implementsIEnumerable<T>
appears to have instance methods such asGroupBy<TSource, TKey>
,
OrderBy<TSource, TKey>
,Average
, and so on. You can see these
additional methods in IntelliSense statement completion when you type
"dot" after an instance of anIEnumerable<T>
type such asList<T>
orArray
.
Count the items from a IEnumerableT without iterating?
IEnumerable
doesn't support this. This is by design. IEnumerable
uses lazy evaluation to get the elements you ask for just before you need them.
If you want to know the number of items without iterating over them you can use ICollection<T>
, it has a Count
property.
IEnumerable to something that I can get a Count from?
Is this actually IEnumerable
instead of IEnumerable<T>
? If so, LINQ won't help you directly. (You can use Cast<T>()
as suggested elsewhere, but that will be relatively slow - in particular, it won't be optimised for IList
/IList<T>
implementations.)
I suggest you write:
public static int Count(this IEnumerable sequence)
{
if (sequence == null)
{
throw new ArgumentNullException("sequence");
}
// Optimisation: won't optimise for collections which
// implement ICollection<T> but not ICollection, admittedly.
ICollection collection = sequence as ICollection;
if (collection != null)
{
return collection.Count;
}
IEnumerator iterator = sequence.GetEnumerator();
try
{
int count = 0;
while (iterator.MoveNext())
{
// Don't bother accessing Current - that might box
// a value, and we don't need it anyway
count++;
}
return count;
}
finally
{
IDisposable disposable = iterator as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
How should I get the length of an IEnumerable?
If you need to read the number of items in an IEnumerable<T>
you have to call the extension method Count
, which in general (look at Matthew comment) would internally iterate through the elements of the sequence and it will return you the number of items in the sequence. There isn't any other more immediate way.
If you know that your sequence is an array, you could cast it and read the number of items using the Length
property.
No, in later versions there isn't any such method.
For implementation details of Count
method, please have a look at here.
Difference between IEnumerable Count() and Length
By calling Count on IEnumerable<T>
I'm assuming you're referring to the extension method Count
on System.Linq.Enumerable
. Length
is not a method on IEnumerable<T>
but rather a property on array types in .Net such as int[]
.
The difference is performance. TheLength
property is guaranteed to be a O(1) operation. The complexity of the Count
extension method differs based on runtime type of the object. It will attempt to cast to several types which support O(1) length lookup like ICollection<T>
via a Count
property. If none are available then it will enumerate all items and count them which has a complexity of O(N).
For example
int[] list = CreateSomeList();
Console.WriteLine(list.Length); // O(1)
IEnumerable<int> e1 = list;
Console.WriteLine(e1.Count()); // O(1)
IEnumerable<int> e2 = list.Where(x => x <> 42);
Console.WriteLine(e2.Count()); // O(N)
The value e2
is implemented as a C# iterator which does not support O(1) counting and hence the method Count
must enumerate the entire collection to determine how long it is.
Is there any Count method for IEnumerable in VB.NET?
Count
is available in VB.NET:
Dim x As New List(Of String)
Dim count As Integer
x.Add("Item 1")
x.Add("Item 2")
count = x.Count
http://msdn.microsoft.com/en-us/library/bb535181.aspx#Y0
Related Topics
Parsing Performance (If, Tryparse, Try-Catch)
What Could Be Causing a System.Typeloadexception
Get Line Number for Xelement Here
Regex Split String But Keep Separators
What Are the Differences Between Various Threading Synchronization Options in C#
Cleanest Way to Invoke Cross-Thread Events
How to Pass Parameters to Activator.Createinstance<T>()
Object Reference Not Set to an Instance of an Object
A Textbox/Richtextbox That Has Syntax Highlighting? [C#]
Hangfire - Multi Tenant, ASP.NET Core - Resolving the Correct Tenant
How to Send a File and Form Data with Httpclient in C#
Is This Thread.Abort() Normal and Safe
Private Inner Classes in C# - Why Aren't They Used More Often