Mega Code Archive

 
Categories / C# Tutorial / LINQ
 

Count elements in a Range

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);        }    } }