Hooked on LINQ

Hooked on LINQ - Developers' Wiki
for .NET Language Integrated Query

Companion book for this site
LINQ to Objects Using C# 4.0:
Using and Extending LINQ to Objects and Parallel LINQ (PLINQ)
Quick Search

Advanced Search »
{TOC}
Namespace:System.Linq
Assembly:System.Core.dll
Extends:IEnumerable<T>

Back to Standard Query Operator Index


Edit

Introduction

The Count operator counts the number of elements in a sequence, or the numer of elements that pass a predicate function.

Edit

Method Signatures

// 1 - Return the count of elements in source.
public static int Count<TSource>(
    this IEnumerable<TSource> source)
 
// 2 - Return the count of elements in sequence that pass the predicate.
public static int Count<TSource>(
    this IEnumerable<TSource> source, 
    Func<TSource, bool> predicate)



Edit

Exceptions

Throws an ArgumentNullException if source or predicate is null.

Edit

Pseudocode

Overload 1
If source is null, throw ArgumentNullException.
If source is of type ICollection<TSource>.
Return source.Count; property. This ia a performance enhancement.
Else, we need to enumerate the collection.
Initialize count result as 0.
Iterate over the source sequence.
count result = previous count result value + 1.
Return the count result value.

Overload 2
If source is null, throw ArgumentNullException.
If predicate is null, throw an ArgumentNullException.
Initialize count result as 0.
Iterate the source sequence
If predicate (current element) returns true, count result = previous count result value + 1.
Return the count result value.

Edit

Loop Count

Overload 1
If the source is of type ICollection, then the Count property of the original source sequence is returned, otherwise the entire sequence is enumerated and counted.


Overload 2
1. The entire sequence is iterated once and predicate evaluated once for every source sequence item.


Edit

Code Samples

==VB Counts how many items are in your Favorites folder==

 
Public Sub Linq()
    Dim FavPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Favorites)
 
    Dim FavSize = (From f In New DirectoryInfo(FavPath).GetFiles() _
                   Select f).Count()
 
    Console.WriteLine("There are {0} files in your Favorites folder.", FavSize)
End Sub 
 

Result may vary,
There are 5 files in your Favorites folder.
Century 21 Broker Properti Jual Beli Sewa Rumah Indonesia

If you would like to comment on this page, click on the Discuss button located on the top-right of each page. Feel free to edit any mistakes or omissions you find. If you have an objection or find in-appropriate content then contact the administrator. This website is not affiliated with Microsoft®, all content and opinions are those of the specific author and some advice, solutions and article may contain unintentional errors - please use care. Other websites by this author: Focused Objective, Geek Speak Decoded.