Count

In this chapter you will learn:

  1. How to count with count operator
  2. Count with filter delegate
  3. supply a predicate
  4. Count with string operator
  5. Count distinct values

How to count with count operator

Count simply enumerates over a sequence, returning the number of items:

using System;//from ja  v  a 2 s. c o m
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int fullCount = new int[] { 5, 6, 7 }.Count();  // 3

        Console.WriteLine(fullCount);

    }
}

The output:

Count with filter delegate

using System;/*from j  av a  2 s  . c o m*/
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class MainClass {
    public static void Main() {
        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

        int oddNumbers = numbers.Count(n => n % 2 == 1);

        Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers);
    }
}

supply a predicate

You can optionally supply a predicate:

using System;/*from  j  a  v  a  2  s. c  o m*/
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int digitCount = "java2s.com".Count(c => char.IsDigit(c)); 
        
        Console.WriteLine(digitCount);
    
    }
}

Count with string operator

using System;//  j  a  va 2  s .c o m
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class MainClass {
    public static void Main() {
        string[] presidents = {"java", "Java", "a", "H", "java2s.com", "Jack"};

        int count = presidents.Count(s => s.StartsWith("j"));
        Console.WriteLine(count);

    }
}

Count distinct values

using System;// j  a v  a2 s. com
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class MainClass {
    public static void Main() {
        int[] factorsOf300 = { 2, 2, 3, 5, 5 };

        int uniqueFactors = factorsOf300.Distinct().Count();

        Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors);
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use DefaultIfEmpty operator
  2. Use DefaultIfEmpty after where clause
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip