Using a Lambda Expression Over a List in C#

This article exemplifies methods for performing several tasks and queries over a set of records in a List.

Sometimes if you have a set of records in a List, it becomes quite easy to query on a list using a Lambda Expression. This article exemplifies methods for performing several tasks and queries over a list. Create a new console project and go to Program.cs See sample code below.

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

namespace LamdaExpressionsOnList
{
    class Program
    {
        static void Main(string[] args)
        {
          //Your Code
        }
    }
}

Suppose we have a “Person” class that has the following members:

class Person  
{  
    public string SSN;  
    public string Name;  
    public string Address;  
    public int Age;  
    public Person(string ssn, string name, string addr, int age)  
    {  
        SSN = ssn;  
        Name = name;  
        Address = addr;  
        Age = age;  
    }  
}  

Now we create a list of the Person objects in which we have to perform several operations like finding a person on certain conditions, removing a person’s record etc. These types of operations can be easily performed using a “Lambda Expression”. We create the list and populate them in the following way:

List<Person> listPersonsInCity = new List<Person>();  

listPersonsInCity.Add(new Person("203456876", "John", "12 Main Street, Newyork, NY", 15));  

listPersonsInCity.Add(new Person("203456877", "SAM", "13 Main Ct, Newyork, NY", 25));  

listPersonsInCity.Add(new Person("203456878", "Elan", "14 Main Street, Newyork, NY", 35));  

listPersonsInCity.Add(new Person("203456879", "Smith", "12 Main Street, Newyork, NY", 45));  

listPersonsInCity.Add(new Person("203456880", "SAM", "345 Main Ave, Dayton, OH", 55));  

listPersonsInCity.Add(new Person("203456881", "Sue", "32 Cranbrook Rd, Newyork, NY", 65));  

listPersonsInCity.Add(new Person("203456882", "Winston", "1208 Alex St, Newyork, NY", 65));  

listPersonsInCity.Add(new Person("203456883", "Mac", "126 Province Ave, Baltimore, NY", 85));  

listPersonsInCity.Add(new Person("203456884", "SAM", "126 Province Ave, Baltimore, NY", 95)); 

Now we see how we can do various complex operations on the list using a one-line simple Lambda expression. 

1. The following code retrieves the first two persons from the list who are older than 60 years:

Console.WriteLine("\n-----------------------------------------------------------------------------");  
Console.WriteLine("Retrieving Top 2 aged persons from the list who are older than 60 years\n");  
foreach (Person person in listPersonsInCity.FindAll(e => (e.Age >= 60)).Take(2).ToList())  
{  
    Console.WriteLine("Name : " + person.Name + " \t\tAge: " + person.Age);  
}
Console Output

2. The following code checks any person’s age that is between 13 and 19 years:

Console.WriteLine("\nChecking whether any person is teen-ager or not...");  
if (listPersonsInCity.Any(e => (e.Age >= 13 && e.Age <= 19)))  
{  
    Console.WriteLine("Yes, we have some teen-agers in the list");  
}
Console Output

3. The following code checks whether all the people’s ages are greater than Ten years or not:

Console.WriteLine("\nCheking whether all the persons are older than 10 years or not...");  
if ( listPersonsInCity.All(e => (e.Age > 10)))  
{  
    Console.WriteLine("Yes, all the persons older than 10 years");  
}
Console Output

4. The following code gets the average of all the people’s ages:

Console.WriteLine("\nGetting Average of all the person's age...");  
double avgAge = listPersonsInCity.Average(e => e.Age);  
Console.WriteLine("The average of all the person's age is: "+ avgAge);

5. The following code checks whether a person having the name ‘SAM’ exists or not:

Console.WriteLine("\nChecking whether a person having name 'SAM' exists or not...");  
if (listPersonsInCity.Exists(e => e.Name == "SAM"))  
{  
    Console.WriteLine("Yes, A person having name  'SAM' exists in our list");  
}
Console Output

6. The following code checks at what position a person having the name ‘Smith’ exists in the list:

Console.WriteLine("\nChecking the index position of a person having name 'Smith' ...");  
int indexForSmith = listPersonsInCity.FindIndex(e => e.Name == "Smith");  
Console.WriteLine("In the list, The index position of a person having name 'Smith' is : " + indexForSmith);
Console Output

7. The following code retrieves the oldest person in the list:

Console.WriteLine("\nGetting the name of the most aged person in the list ...");  
Person p = listPersonsInCity.First(m=> m.Age == (listPersonsInCity.Max(e => e.Age)));  
Console.WriteLine("The most aged person in our list is: "+ p.Name +" whose age is: "+ p.Age);
Console Output

8. The following code gets the total of all the people’s ages:

Console.WriteLine("\nGetting Sum of all the person's age...");  
int sumOfAges = listPersonsInCity.Sum(e => e.Age);  
Console.WriteLine("The sum of all the persons's age = "+ sumOfAges);
Console Output

9. The following code skips each person whose age is less than 60:

Console.WriteLine("\nSkipping every person whose age is less than 60 years...");  
foreach (Person pers in listPersonsInCity.SkipWhile(e => e.Age < 60))  
{  
Console.WriteLine("Name : "+ pers.Name + " \t\tAge: "+ pers.Age);  
}
Console Output

10. The following code retrieves all the people until we find a person with a name beginning with any letter other than “S” :

Console.WriteLine("Displaying the persons until we find a person with name starts with other than 'S'");  
foreach (Person pers in listPersonsInCity.TakeWhile(e => e.Name.StartsWith("J")))  
{  
    Console.WriteLine("Name : " + pers.Name + " \t\tAge: " + pers.Age);  
}
Console Output

11. The following code checks whether all the people have their SSN or not:

Console.WriteLine("\nChecking all the persons have SSN or not ...");  
if(listPersonsInCity.TrueForAll(e => e.SSN != null))  
{  
    Console.WriteLine("No person is found without SSN");  
}
Console Output

12. The following code removes all the people having the name “SAM”:

Console.WriteLine("\nRemoving all the persons record from list that have "SAM" name");  
listPersonsInCity.RemoveAll(e => (e.Name == "SAM"));  
if (listPersonsInCity.TrueForAll(e => e.Name != "SAM"))  
{  
    Console.WriteLine("No person is found with 'SAM' name in current list");  
}
Console Output

13. The following code searches for the person having “203456876” as their SSN:

Console.WriteLine("\nFinding the person whose SSN = 203456876 in the list");  
Person oPerson = listPersonsInCity.Find(e => (e.SSN == "203456876"));  
Console.WriteLine("The person having SSN '203456876' is : " + oPerson.Name + " \t\tAge: " + oPerson.Age);
Console Output

Lambda Expressions are a powerful addition to C# Programming. This article attempts to describe lambda expressions in simple terms to pave the way for some powerful uses of this construct.

C# Analog Clock Program

In this tutorial we are going to use a bit of graphics class to design a C# analog clock. We have also used a timer to continuously move our clock’s pointer.

Concept

  • We will first initialize some angle values to second, minute, hour hand.
  • Then draw the clock using the graphics class, save it as a bitmap variable and load it in the picturebox.
  • Finally Use the timer to move the second hand.

Instructions

  • Create a new windows form applicaton project in visual c#.
  • Add a picture box on the form.
  • Double click the form to switch to code view. 
  • Delete all the existing code and paste the code given below.

C# Analog Clock Program

Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace AnalogClock
{
    public partial class Form1 : Form
    {
        Timer t = new Timer();
 
        int WIDTH = 300, HEIGHT = 300, secHAND = 140, minHAND = 110, hrHAND = 80;
 
        //center
        int cx, cy;
 
        Bitmap bmp;
        Graphics g;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            //create bitmap
            bmp = new Bitmap(WIDTH + 1, HEIGHT + 1);
 
            //center
            cx = WIDTH / 2;
            cy = HEIGHT / 2;
 
            //backcolor
            this.BackColor = Color.White;
 
            //timer
            t.Interval = 1000;      //in millisecond
            t.Tick += new EventHandler(this.t_Tick);
            t.Start();
        }
 
        private void t_Tick(object sender, EventArgs e)
        {
            //create graphics
            g = Graphics.FromImage(bmp);
 
            //get time
            int ss = DateTime.Now.Second;
            int mm = DateTime.Now.Minute;
            int hh = DateTime.Now.Hour;
 
            int[] handCoord = new int[2];
 
            //clear
            g.Clear(Color.White);
 
            //draw circle
            g.DrawEllipse(new Pen(Color.Black, 1f), 0, 0, WIDTH, HEIGHT);
 
            //draw figure
            g.DrawString("12", new Font("Arial", 12), Brushes.Black, new PointF(140, 2));
            g.DrawString("3", new Font("Arial", 12), Brushes.Black, new PointF(286, 140));
            g.DrawString("6", new Font("Arial", 12), Brushes.Black, new PointF(142, 282));
            g.DrawString("9", new Font("Arial", 12), Brushes.Black, new PointF(0, 140));
 
            //second hand
            handCoord = msCoord(ss, secHAND);
            g.DrawLine(new Pen(Color.Red, 1f), new Point(cx, cy), new Point(handCoord[0], handCoord[1]));
 
            //minute hand
            handCoord = msCoord(mm, minHAND);
            g.DrawLine(new Pen(Color.Black, 2f), new Point(cx, cy), new Point(handCoord[0], handCoord[1]));
 
            //hour hand
            handCoord = hrCoord(hh % 12, mm, hrHAND);
            g.DrawLine(new Pen(Color.Gray, 3f), new Point(cx, cy), new Point(handCoord[0], handCoord[1]));
 
            //load bmp in picturebox1
            pictureBox1.Image = bmp;
 
            //disp time
            this.Text = "Analog Clock -  " + hh + ":" + mm + ":" + ss;
 
            //dispose
            g.Dispose();
        }
 
        //coord for minute and second hand
        private int[] msCoord(int val, int hlen)
        {
            int[] coord = new int[2];
            val *= 6;   //each minute and second make 6 degree
 
            if (val >= 0 && val <= 180)
            {
                coord[0] = cx + (int)(hlen * Math.Sin(Math.PI * val / 180));
                coord[1] = cy - (int)(hlen * Math.Cos(Math.PI * val / 180));
            }
            else
            {
                coord[0] = cx - (int)(hlen * -Math.Sin(Math.PI * val / 180));
                coord[1] = cy - (int)(hlen * Math.Cos(Math.PI * val / 180));
            }
            return coord;
        }
 
        //coord for hour hand
        private int[] hrCoord(int hval, int mval, int hlen)
        {
            int[] coord = new int[2];
 
            //each hour makes 30 degree
            //each min makes 0.5 degree
            int val = (int)((hval * 30) + (mval * 0.5));
 
            if (val >= 0 && val <= 180)
            {
                coord[0] = cx + (int)(hlen * Math.Sin(Math.PI * val / 180));
                coord[1] = cy - (int)(hlen * Math.Cos(Math.PI * val / 180));
            }
            else
            {
                coord[0] = cx - (int)(hlen * -Math.Sin(Math.PI * val / 180));
                coord[1] = cy - (int)(hlen * Math.Cos(Math.PI * val / 180));
            }
            return coord;
        }
    }
}