Sunday, August 17, 2008

Exploring LINQ Functions - Select, Min, Max, Average, ToArray()

Here is a sample program which will help you to learn some basic functions of LINQ.
The example is of a company in which there are some employees. We will try to explore some functions that are related to this example.

We will
1) list all the employees
2) Find Max salaried employee
3) Find Min Salaried Employee
4) Average salary paid by the company

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

namespace SampleLINQ
class Program
static void Main(string[] args)
//Create a list of Employees
List LEmp = new List();
LEmp.Add(new Employee() { Name = "Emp1", Age = 24, salary = 40000 });
LEmp.Add(new Employee() { Name = "Emp2", Age = 25, salary = 35000 });
LEmp.Add(new Employee() { Name = "Emp3", Age = 24, salary = 20000 });
LEmp.Add(new Employee() { Name = "Emp4", Age = 25, salary = 20000 });
LEmp.Add(new Employee() { Name = "Emp5", Age = 26, salary = 25000 });

//Names of employees
Console.WriteLine("List Of employees");
Console.WriteLine(string.Join("\n", LEmp.Select(emp => emp.Name).ToArray()));

//Average salary paid
Console.WriteLine("Average Salary Paid");
Console.WriteLine(LEmp.Average(emp => emp.salary));

//Find employees with Max Salary and print
Employee[] MaxSalary = (from mSal in LEmp
where mSal.salary == LEmp.Max(emp => emp.salary)
select mSal).ToArray();

Console.WriteLine("Highest salaried Employees");
Console.WriteLine(string.Join(",", MaxSalary.Select(emp => emp.Name).ToArray()));

//Find employees with Min Salary and print
Employee[] MinSalary = (from mSal in LEmp
where mSal.salary == LEmp.Min(emp => emp.salary)
select mSal).ToArray();

Console.WriteLine("Least salaried Employees");
Console.WriteLine(string.Join(",", MinSalary.Select(emp => emp.Name).ToArray()));

//Show the console

//The following line can also be used to fetch the names of highest or least salaried employee
//All the above operations are done in a single line.
//Console.WriteLine(string.Join(",", LCust.Where(cust => cust.salary == LCust.Max(emp => emp.salary)).Select(cust => cust.Name).ToArray()));


public class Employee
public string Name

public int Age

public double salary

1 comment:

vishnuprasath said...

It's useful information
View salary information for thousands of different companies.
Search for salaries by company, city or profession.
Job Search