LINQ example

using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Text;    
  
namespace LINQSamples    
{    
    public class Person    
    {   
        public string Name { get; set; }   
        public int Age { get; set; }   
     
        public override string ToString()   
        {   
            return this.Name + " " + this.Age;   
        }   
    }   
     
    class Program   
    {   
        static void Main(string[] args)   
        {   
            List persons = new List();   
     
            persons.Add(new Person() { Name = "Berend", Age = 38 });   
            persons.Add(new Person() { Name = "Nynke", Age = 6 });  
            persons.Add(new Person() { Name = "Marije", Age = 5 });   
            persons.Add(new Person() { Name = "Bennie", Age = 2 });   
            persons.Add(new Person() { Name = "Marian", Age = 38 });   
            Console.WriteLine("All persons:");   
            foreach (var p in persons)   
            {   
                Console.WriteLine(p);   
            }   
            Console.WriteLine();   
    
            Console.WriteLine("All persons order by name descending:");   
            var query = from person in persons orderby person.Name descending select person;   
            foreach (var p in query)   
            {   
                Console.WriteLine(p.Name);   
            }   
            Console.WriteLine();   
    
            Console.WriteLine("# of persons that are 6 years old:");   
            Console.WriteLine(persons.Count(person => person.Age == 6).ToString());   
    
            Console.ReadKey();   
        }   
    }   
}
Share

Leave a Reply

Your email address will not be published. Required fields are marked *