Count elements in a Range : Count « LINQ « C# / CSharp Tutorial






using System;
using System.Collections.Generic;
using System.Linq;

class Item{
   public int Width { get; set; }
   public int Length { get; set; }

   public override string ToString(){
       return string.Format("Width: {0}, Length: {1}", Width, Length);
   }
}
    
class MainClass{
   static void Main(string[] args){
       List<Item> items = new List<Item>{ 
            new Item { Length = 0, Width = 5 },
            new Item { Length = 1, Width = 6 },
            new Item { Length = 2, Width = 7 },
            new Item { Length = 3, Width = 8 },
            new Item { Length = 4, Width = 9 }
       };
       ShowList(items);
       Console.WriteLine("The number of items: {0}", items.Count());
       var list = Enumerable.Range(1, 25);
       ShowList(list);
       Console.WriteLine("Total Count: {0}, Count the even numbers: {1}",list.Count(), list.Count(n => n % 2 == 0));         

   }
   static void ShowList<T>(IEnumerable<T> list){
       foreach (var item in list){
          Console.WriteLine(item);
       }
   }
}








22.29.Count
22.29.1.Count with string value
22.29.2.Count with string operator
22.29.3.The aggregation operators return a scalar value
22.29.4.Use Aggregate Operators: Count
22.29.5.Conditional Count
22.29.6.Nested Count
22.29.7.Numeric Aggregates: count
22.29.8.Count elements in a Range