Count
In this chapter you will learn:
- How to count with count operator
- Count with filter delegate
- supply a predicate
- Count with string operator
- 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:
Home » C# Tutorial » Linq Operators