Whats the best/easiest way to obtain a count of items within an IEnumerable collection without enumerating over all of the items in the collection?
Possible with LIN
An IEnumerable will have to iterate through every item. to get the full count. If you just need to check if there is one or more items in an IEnumerable a more efficient method is to check if there are any. Any() only check to see there is a value and does not loop through everything.
IEnumerable myStrings = new List(){"one","two", "three"};
bool hasValues = myStrings.Any();
Not possible with LINQ, as calling .Count(...) does enumerate the collection. If you're running into the problem where you can't iterate through a collection twice, try this:
List<MyTableItem> myList = dataContext.MyTable.ToList();
int myTableCount = myList.Count;
foreach (MyTableItem in myList)
{
...
}
Use this.
IEnumerable list =..........;
list.OfType<T>().Count()
it will return the count.
You will have to enumerate to get a count. Other constructs like the List keep a running count.
In any case, you have to loop through it. Linq offers the Count
method:
var result = myenum.Count();