Introduction This tutorial provides samples for LINQ to objects queries. The examples created and consolidated with sample data similar to MSDN LINQ 101 Samples but with ease, simple and more user-friendly. There are 79 samples provided in this tutorial. Consolidated Code is provided at the beginning itself.
LINQ Samples Classification
- Restriction Operators
- Projection Operators
- Partioning Operators
- Ordering Operators
- Grouping Operators
- Conversion Operators
- Element Operators
- Generation Operators
- Quantifiers
- Aggregate Operators
- Concat/SequenceEqual Operators
- Join Operations
- LINQ Execution
LINQSamples.cs file (Code for Employee, Department Classes and Data, LINQ Sample Methods) |
using System;
using System.Collections.Generic;
using System.Linq;
namespace CSharpSamples
{
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public double Salary { get; set; }
public DateTime DateOfJoining { get; set; }
}
public class Department
{
public int ID { get; set; }
public string Name { get; set; }
}
public class CaseInsensitiveComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return string.Compare(x, y, StringComparison.OrdinalIgnoreCase);
}
}
public class LINQSamples
{
public List<Employee> EmployeeList { get; set; }
public List<Department> DepartmentList { get; set; }
public LINQSamples()
{
this.EmployeeList = GetEmployeeList();
this.DepartmentList = GetDepartmentList();
}
public List<Employee> GetEmployeeList()
{
List<Employee> employeeList = new List<Employee>()
{
new Employee()
{
ID = 1,
Name = "Anil",
Department = "Information Technology",
Salary = 20000,
DateOfJoining = new DateTime(2006, 09, 11)
},
new Employee()
{
ID = 2,
Name = "Prasad",
Department = "Information Technology",
Salary = 25000,
DateOfJoining = new DateTime(2005, 12, 1)
},
new Employee()
{
ID = 3,
Name = "Mohan",
Department = "Information Technology",
Salary = 50000,
DateOfJoining = new DateTime(2003, 5, 18)
},
new Employee()
{
ID = 4,
Name = "Praveen",
Department = "Finance",
Salary = 22000,
DateOfJoining = new DateTime(2010, 2, 10)
},
new Employee()
{
ID = 5,
Name = "Ravi",
Department = "Finance",
Salary = 40000,
DateOfJoining = new DateTime(2007, 6, 16)
},
new Employee()
{
ID = 6,
Name = "Krishna",
Department = "Human Resources",
Salary = 80000,
DateOfJoining = new DateTime(2003, 5, 18)
},
new Employee()
{
ID = 7,
Name = "Avinash",
Department = "Human Resources",
Salary = 32000,
DateOfJoining = new DateTime(2011, 3, 24)
},
new Employee()
{
ID = 8,
Name = "Pankaj",
Department = "Admin",
Salary = 28000,
DateOfJoining = new DateTime(2009, 4, 9)
},
new Employee()
{
ID = 9,
Name = "Narendra",
Department = "Admin",
Salary = 18000,
DateOfJoining = new DateTime(2008, 11, 19)
},
new Employee()
{
ID = 10,
Name = "Kumar",
Department = "Admin",
Salary = 10000,
DateOfJoining = new DateTime(2011, 09, 8)
}
};
return employeeList;
}
public List<Department> GetDepartmentList()
{
List<Department> departmentList = new List<Department>()
{
new Department()
{
ID = 1,
Name = "Admin"
},
new Department()
{
ID = 2,
Name = "Finance"
},
new Department()
{
ID = 3,
Name = "Human Resources"
},
new Department()
{
ID = 4,
Name = "Information Technology"
},
new Department()
{
ID = 5,
Name = "Sales"
}
};
return departmentList;
}
public string FormatEmployeeInformation(Employee emp)
{
return string.Format("ID: {0} Name: {1} Department: {2} Salary: {3} DOJ: {4}",
emp.ID, emp.Name, emp.Department, emp.Salary, emp.DateOfJoining.ToString("dd-MMM-yyyy"));
}
#region Restriction Operators
// Where - Simple 1
public void Linq1()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums = from n in numbers
where n < 6
select n;
Console.WriteLine();
Console.WriteLine("Numers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("Numbers < 6:");
foreach (var x in lowNums)
{
Console.WriteLine(x);
}
Console.WriteLine();
}
// Where - Simple 2
public void Linq2()
{
var empWithSal10K = from e in EmployeeList
where e.Salary == 10000
select e;
Console.WriteLine();
Console.WriteLine("Employees having Salary equals to 10000:");
Console.WriteLine();
foreach (var emp in empWithSal10K)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
// Where - Simple 3
public void Linq3()
{
var employeesJoinedAfter2009WithMoreThan15K = from e in EmployeeList
where e.DateOfJoining > new DateTime(2009, 12, 31)
&& e.Salary > 15000
select e;
Console.WriteLine();
Console.WriteLine("Employees joined after 2009 and having salary more than 15000:");
Console.WriteLine();
foreach (var emp in employeesJoinedAfter2009WithMoreThan15K)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
// Where - Indexed
public void Linq4()
{
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var shortDigits = digits.Where((digit, index) => digit.Length < index);
Console.WriteLine();
Console.WriteLine("Digits List: { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" }");
Console.WriteLine();
Console.WriteLine("Short digits:");
foreach (var d in shortDigits)
{
Console.WriteLine("The word {0} is shorter than its value.", d);
}
Console.WriteLine();
}
#endregion
#region Projection Operators
// Select - Simple 1
public void Linq5()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numsPlusOne = from n in numbers
select n + 1;
Console.WriteLine();
Console.WriteLine("Numbers { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine("Numbers + 1:");
foreach (var i in numsPlusOne)
{
Console.WriteLine(i);
}
Console.WriteLine();
}
// Select - Simple 2
public void Linq6()
{
var employeeNames = from e in EmployeeList
select e.Name;
Console.WriteLine();
Console.WriteLine("List of Employees:");
Console.WriteLine();
foreach (var empName in employeeNames)
{
Console.WriteLine(empName);
}
Console.WriteLine();
}
// Select - Transformation
public void Linq7()
{
int[] numbers = { 4, 5, 1, 3, 9, 8, 6, 7, 2, 0 };
string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var textNums = from n in numbers
select strings[n];
Console.WriteLine();
Console.WriteLine("Numbers List: { 4, 5, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine("Strings List: { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" }");
Console.WriteLine();
Console.WriteLine("Number strings:");
foreach (var s in textNums)
{
Console.WriteLine(s);
}
Console.WriteLine();
}
// Select - Anonymous Types 1
public void Linq8()
{
string[] words = { "MicroSOFT", "GooGle", "aDOBE", "aPPle" };
var upperLowerWords = from w in words
select new
{
Upper = w.ToUpper(),
Lower = w.ToLower()
};
Console.WriteLine();
Console.WriteLine("Input Words: { \"MicroSOFT\", \"GooGle\", \"aDOBE\", \"aPPle\" }");
Console.WriteLine();
foreach (var ul in upperLowerWords)
{
Console.WriteLine("UPPERCASE: {0}\t lowercase: {1}", ul.Upper, ul.Lower);
}
Console.WriteLine();
}
// Select - Anonymous Types 2
public void Linq9()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var digitOddEvens = from n in numbers
select new
{
Digit = strings[n],
Even = (n % 2 == 0)
};
Console.WriteLine();
Console.WriteLine("Even/Odd Check:");
Console.WriteLine();
foreach (var d in digitOddEvens)
{
Console.WriteLine("The digit {0} is {1}.", d.Digit, d.Even ? "even" : "odd");
}
Console.WriteLine();
}
// Select - Anonymous Types 3
public void Linq10()
{
var employeesInfo = from e in EmployeeList
select new
{
e.Name,
e.Department,
Salary = e.Salary
};
Console.WriteLine();
Console.WriteLine("Employees Info:");
Console.WriteLine();
foreach (var empInfo in employeesInfo)
{
Console.WriteLine("<{0}> is in the Department <{1}> and having salary <{2}>.", empInfo.Name, empInfo.Department, empInfo.Salary);
}
Console.WriteLine();
}
// Select - Indexed
public void Linq11()
{
int[] numbers = { 4, 5, 1, 3, 9, 8, 6, 7, 2, 0 };
var numsInPlace = numbers.Select((num, index) => new { Num = num, InPlace = (num == index) });
Console.WriteLine();
Console.WriteLine("Numbers List: { 4, 5, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("Number: In-Place?");
Console.WriteLine();
foreach (var n in numsInPlace)
{
Console.WriteLine("{0}: {1}", n.Num, n.InPlace);
}
Console.WriteLine();
}
// Select - Filtered
public void Linq12()
{
var employeesInfo = from e in EmployeeList
where e.Salary > 20000
select e;
Console.WriteLine();
Console.WriteLine("Employees having Salary > 20000:");
Console.WriteLine();
foreach (var emp in employeesInfo)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
// SelectMany - Compound from 1
public void Linq13()
{
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var pairs = from a in numbersA
from b in numbersB
where a < b
select new { a, b };
Console.WriteLine();
Console.WriteLine("Set A: { 0, 2, 4, 5, 6, 8, 9 }");
Console.WriteLine("Set B: { 1, 3, 5, 7, 8 }");
Console.WriteLine();
Console.WriteLine("Pairs where a < b:");
Console.WriteLine();
foreach (var pair in pairs)
{
Console.WriteLine("{0} is less than {1}", pair.a, pair.b);
}
Console.WriteLine();
}
// SelectMany - Compound from 2
public void Linq14()
{
int[] salaries = { 10000, 15000, 20000, 25000 };
var empSalaries = from e in EmployeeList
from s in salaries
where e.Salary > s
select new
{
e.Name,
e.Salary,
s
};
Console.WriteLine();
Console.WriteLine("Salary Comparision with the Set: { 10000, 15000, 20000, 25000 }");
Console.WriteLine();
foreach (var item in empSalaries)
{
Console.WriteLine(item.Name + " Salary(" + item.Salary + ") is more than " + item.s.ToString());
}
Console.WriteLine();
}
// SelectMany - Multiple from
public void Linq15()
{
int[] salaries = { 10000, 15000, 20000, 25000 };
var empSalaries = from e in EmployeeList
where e.Name.ToUpper().StartsWith("P")
from s in salaries
where e.Salary > s
select new
{
e.Name,
e.Salary,
s
};
Console.WriteLine();
Console.WriteLine("Salary Comparision of Employees whose names start with \"P\" with the Set: { 10000, 15000, 20000, 25000 }");
Console.WriteLine();
foreach (var item in empSalaries)
{
Console.WriteLine(item.Name + " Salary(" + item.Salary + ") is more than " + item.s.ToString());
}
Console.WriteLine();
}
#endregion
#region Partitioning Operators
// Take - Simple
public void Linq16()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var first4Numbers = numbers.Take(4);
Console.WriteLine();
Console.WriteLine("Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("First 4 Numbers:");
Console.WriteLine();
foreach (var n in first4Numbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
// TakeWhile - Simple
public void Linq17()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var firstNumbersLessThan7 = numbers.TakeWhile(n => n < 7);
Console.WriteLine();
Console.WriteLine("Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("First Numbers less than 7:");
foreach (var n in firstNumbersLessThan7)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
// TakeWhile - Indexed
public void Linq18()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index);
Console.WriteLine();
Console.WriteLine("Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("First numbers not less than their position:");
Console.WriteLine();
foreach (var n in firstSmallNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
// Skip - Simple
public void Linq19()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var allButFirst3Numbers = numbers.Skip(3);
Console.WriteLine();
Console.WriteLine("Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("All but first 3 numbers:");
Console.WriteLine();
foreach (var n in allButFirst3Numbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
// SkipWhile - Simple
public void Linq20()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0);
Console.WriteLine();
Console.WriteLine("Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("All elements starting from first element divisible by 3:");
Console.WriteLine();
foreach (var n in allButFirst3Numbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
// SkipWhile - Indexed
public void Linq21()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var laterNumbers = numbers.SkipWhile((n, index) => n >= index);
Console.WriteLine();
Console.WriteLine("Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("All elements starting from first element greater than than its position:");
Console.WriteLine();
foreach (var n in laterNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
#endregion
#region Ordering Operators
// OrderBy - Simple 1
public void Linq22()
{
string[] words = { "Microsoft", "Google", "Adobe", "Apple", "IBM" };
var sortedWords = from w in words
orderby w
select w;
Console.WriteLine();
Console.WriteLine("Input Words: { \"Microsoft\", \"Google\", \"Adobe\", \"Apple\", \"IBM\" }");
Console.WriteLine();
Console.WriteLine("The sorted list of words:");
Console.WriteLine();
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
Console.WriteLine();
}
// OrderBy - Simple 2
public void Linq23()
{
var sortedEmployees = from e in EmployeeList
orderby e.Name
select e;
Console.WriteLine();
Console.WriteLine("Employees List in Name Ascending Order:");
Console.WriteLine();
foreach (var emp in sortedEmployees)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
// OrderBy - Comparer
public void Linq24()
{
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
var sortedWords = words.OrderBy(a => a, new CaseInsensitiveComparer());
Console.WriteLine();
Console.WriteLine("Input Words: { \"aPPLE\", \"AbAcUs\", \"bRaNcH\", \"BlUeBeRrY\", \"ClOvEr\", \"cHeRry\" }");
Console.WriteLine();
Console.WriteLine("The sorted(A-Z) list of words:");
Console.WriteLine();
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
Console.WriteLine();
}
// OrderByDescending - Simple 1
public void Linq25()
{
double[] doubles = { 3.2, 1.3, 5.9, 7.1, 4.7 };
var sortedDoubles = from d in doubles
orderby d descending
select d;
Console.WriteLine();
Console.WriteLine("Input Decimals: { 3.2, 1.3, 5.9, 7.1, 4.7 }");
Console.WriteLine();
Console.WriteLine("The doubles from highest to lowest:");
Console.WriteLine();
foreach (var d in sortedDoubles)
{
Console.WriteLine(d);
}
Console.WriteLine();
}
// OrderByDescending - Simple 2
public void Linq26()
{
var sortedEmployees = from e in EmployeeList
orderby e.Salary descending
select e;
Console.WriteLine();
Console.WriteLine("Employees List from Highest to Lowest Salary:");
Console.WriteLine();
foreach (var emp in sortedEmployees)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
// OrderByDescending - Comparer
public void Linq27()
{
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
var sortedWords = words.OrderByDescending(a => a, new CaseInsensitiveComparer());
Console.WriteLine();
Console.WriteLine("Input Words: { \"aPPLE\", \"AbAcUs\", \"bRaNcH\", \"BlUeBeRrY\", \"ClOvEr\", \"cHeRry\" }");
Console.WriteLine();
Console.WriteLine("The sorted(Z-A) list of words:");
Console.WriteLine();
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
Console.WriteLine();
}
// ThenBy - Simple
public void Linq28()
{
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var sortedDigits = digits.OrderBy(d => d.Length).ThenBy(d => d);
Console.WriteLine();
Console.WriteLine("Input Words: { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" }");
Console.WriteLine();
Console.WriteLine("Sorted Words first by length and then by Alphabetical order:");
Console.WriteLine();
foreach (var d in sortedDigits)
{
Console.WriteLine(d);
}
Console.WriteLine();
}
// ThenBy - Comparer
public void Linq29()
{
string[] words = { "apple", "abacus", "branch", "blueberry", "clover", "cherry" };
var sortedWords = words.OrderBy(a => a.Length)
.ThenBy(a => a, new CaseInsensitiveComparer());
Console.WriteLine();
Console.WriteLine("Input Words: { \"apple\", \"abacus\", \"branch\", \"blueberry\", \"clover\", \"cherry\" }");
Console.WriteLine();
Console.WriteLine("The sorted list of words first by length and next by alphabetical order(A-Z):");
Console.WriteLine();
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
Console.WriteLine();
}
// ThenByDescending - Simple
public void Linq30()
{
var sortedEmployees = from e in EmployeeList
orderby e.Department, e.Salary descending
select e;
Console.WriteLine();
Console.WriteLine("Employees List in Department Ascending Order and Salary Descending Order:");
Console.WriteLine();
foreach (var emp in sortedEmployees)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
// ThenByDescending - Comparer
public void Linq31()
{
string[] words = { "apple", "abacus", "branch", "blueberry", "clover", "cherry" };
var sortedWords = words.OrderBy(a => a.Length)
.ThenByDescending(a => a, new CaseInsensitiveComparer());
Console.WriteLine();
Console.WriteLine("Input Words: { \"apple\", \"abacus\", \"branch\", \"blueberry\", \"clover\", \"cherry\" }");
Console.WriteLine();
Console.WriteLine("The sorted list of words first by length ascending and next by alphabetical order descending(Z-A):");
Console.WriteLine();
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
Console.WriteLine();
}
// Reverse
public void Linq32()
{
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var reversedIDigits = (from d in digits
where d[1] == 'i'
select d).Reverse();
Console.WriteLine();
Console.WriteLine("Input Words: { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" }");
Console.WriteLine();
Console.WriteLine("A backwards list of the digits with a second character of 'i':");
Console.WriteLine();
foreach (var d in reversedIDigits)
{
Console.WriteLine(d);
}
Console.WriteLine();
}
#endregion
#region Grouping Operators
// GroupBy - Simple 1
public void Linq33()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numberGroups = from n in numbers
group n by n % 4 into g
select new
{
Remainder = g.Key,
Numbers = g
};
Console.WriteLine();
Console.WriteLine("Input Numbers: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
foreach (var g in numberGroups)
{
Console.WriteLine("Numbers with a remainder of {0} when divided by 5:", g.Remainder);
foreach (var n in g.Numbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Console.WriteLine();
string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" };
var wordGroups = from w in words
group w by w[0] into g
select new
{
FirstLetter = g.Key,
Words = g
};
Console.WriteLine("Input Words: { \"blueberry\", \"chimpanzee\", \"abacus\", \"banana\", \"apple\", \"cheese\" }");
Console.WriteLine();
foreach (var g in wordGroups)
{
Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter);
foreach (var w in g.Words)
{
Console.WriteLine(w);
}
Console.WriteLine();
}
Console.WriteLine();
}
// GroupBy - Simple 2
public void Linq34()
{
var deptEmployees = from e in EmployeeList
group e by e.Department into Employees
select new
{
Department = Employees.Key,
Employees
};
Console.WriteLine();
Console.WriteLine("Departmentwise Employees List:");
Console.WriteLine();
foreach (var dept in deptEmployees)
{
Console.WriteLine("Department: " + dept.Department);
foreach (var emp in dept.Employees)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
Console.WriteLine();
}
// GroupBy - Nested
public void Linq35()
{
var deptEmployees = from e in EmployeeList
group e by e.Department into DEPTGRPS
orderby DEPTGRPS.Key
select new
{
Dept = DEPTGRPS.Key,
DeptGroups = from e1 in DEPTGRPS
group e1 by e1.DateOfJoining.Year into YearGroups
orderby YearGroups.Key
select new
{
year = YearGroups.Key,
emps = YearGroups
}
};
Console.WriteLine();
Console.WriteLine("Department wise and joining year wise Employees List:");
Console.WriteLine();
foreach (var dept in deptEmployees)
{
Console.WriteLine("Department: " + dept.Dept);
foreach (var emp in dept.DeptGroups)
{
Console.WriteLine("Joining Year: " + emp.year.ToString());
foreach (var item in emp.emps)
{
Console.WriteLine(FormatEmployeeInformation(item));
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine();
}
Console.WriteLine();
}
#endregion
#region Set operators
// Distinct - 1
public void Linq36()
{
int[] factorsOf300 = { 2, 2, 3, 5, 5 };
var uniqueFactors = factorsOf300.Distinct();
Console.WriteLine();
Console.WriteLine("Prime factors of 300: { 2, 2, 3, 5, 5 }");
Console.WriteLine();
Console.WriteLine("Unique Prime factors of 300:");
Console.WriteLine();
foreach (var f in uniqueFactors)
{
Console.WriteLine(f);
}
Console.WriteLine();
}
// Distinct - 2
public void Linq37()
{
var departments = (from e in EmployeeList
select e.Department).Distinct();
Console.WriteLine();
Console.WriteLine("List of All Departments:");
Console.WriteLine();
foreach (var dept in departments)
{
Console.WriteLine(dept);
}
Console.WriteLine();
}
// Union - 1
public void Linq38()
{
int[] numbersA = { 0, 2, 4, 6, 8 };
int[] numbersB = { 0, 3, 6, 9 };
var uniqueNumbers = numbersA.Union(numbersB);
Console.WriteLine();
Console.WriteLine("Input Arrays: { 0, 2, 4, 6, 8 }, { 0, 3, 6, 9 }");
Console.WriteLine();
Console.WriteLine("Unique Numbers from both the arrays:");
Console.WriteLine();
foreach (var n in uniqueNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
// Union - 2
public void Linq39()
{
var empFirstChars = from e in EmployeeList
select e.Name[0];
var deptFirstChars = from e in EmployeeList
select e.Department[0];
var uniqueFirstChars = empFirstChars.Union(deptFirstChars);
Console.WriteLine();
Console.WriteLine("Unique first letters from Employee Names and Department Names:");
Console.WriteLine();
foreach (var ch in uniqueFirstChars)
{
Console.WriteLine(ch);
}
Console.WriteLine();
}
// Intersect - 1
public void Linq40()
{
int[] numbersA = { 0, 2, 4, 6, 8 };
int[] numbersB = { 0, 3, 6, 9 };
var commonNumbers = numbersA.Intersect(numbersB);
Console.WriteLine();
Console.WriteLine("Input Arrays: { 0, 2, 4, 6, 8 }, { 0, 3, 6, 9 }");
Console.WriteLine();
Console.WriteLine("Common Numbers from both the arrays:");
Console.WriteLine();
foreach (var n in commonNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
// Intersect - 2
public void Linq41()
{
var empFirstChars = from e in EmployeeList
select e.Name[0];
var deptFirstChars = from e in EmployeeList
select e.Department[0];
var commonFirstChars = empFirstChars.Intersect(deptFirstChars);
Console.WriteLine();
Console.WriteLine("Common first letters from Employee Names and Department Names:");
Console.WriteLine();
foreach (var ch in commonFirstChars)
{
Console.WriteLine(ch);
}
Console.WriteLine();
}
// Except - 1
public void Linq42()
{
int[] numbersA = { 0, 2, 4, 6, 8 };
int[] numbersB = { 0, 3, 6, 9 };
var uniqueNumbers = numbersA.Except(numbersB);
Console.WriteLine();
Console.WriteLine("Input Arrays: { 0, 2, 4, 6, 8 }, { 0, 3, 6, 9 }");
Console.WriteLine();
Console.WriteLine("Numbers in first array but not in second array:");
Console.WriteLine();
foreach (var n in uniqueNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
// Except - 2
public void Linq43()
{
var empFirstChars = from e in EmployeeList
select e.Name[0];
var deptFirstChars = from e in EmployeeList
select e.Department[0];
var commonFirstChars = empFirstChars.Except(deptFirstChars);
Console.WriteLine();
Console.WriteLine("First letters from Employee Names, but not from Department Names:");
Console.WriteLine();
foreach (var ch in commonFirstChars)
{
Console.WriteLine(ch);
}
Console.WriteLine();
}
#endregion
#region Conversion Operators
// ToArray
public void Linq44()
{
double[] doubles = { 1.5, 2.3, 1.8, 4.2, 3.6, 5.4 };
var sortedDoubles = from d in doubles
orderby d descending
select d;
var doublesArray = sortedDoubles.ToArray();
Console.WriteLine();
Console.WriteLine("Array of Doubles: { 1.5, 2.3, 1.8, 4.2, 3.6, 5.4 }");
Console.WriteLine();
Console.WriteLine("Doubles from highest to lowest:");
Console.WriteLine();
for (int d = 0; d < doublesArray.Length; d++)
{
Console.WriteLine(doublesArray[d]);
}
Console.WriteLine();
}
// ToList
public void Linq45()
{
var employees = from e in EmployeeList
orderby e.Department
select e.Name;
var empList = employees.ToList();
Console.WriteLine();
Console.WriteLine("The Sorted Employee List:");
Console.WriteLine();
foreach (var e in empList)
{
Console.WriteLine(e);
}
Console.WriteLine();
}
// ToDictionary
public void Linq46()
{
var salaryRecords = new[]
{
new { Name = "Anil", Salary = 20000 },
new { Name = "Prasad" , Salary = 25000 },
new { Name = "Mohan", Salary = 50000 }
};
var salaryRecordsDict = salaryRecords.ToDictionary(sr => sr.Name);
Console.WriteLine();
Console.WriteLine("Salary Records: \n\n{ Name = \"Anil\", Salary = 20000 }\n{ Name = \"Prasad\" , Salary = 25000 }\n{ Name = \"Mohan\", Salary = 50000 }");
Console.WriteLine();
Console.WriteLine("Salary Records Dictionary Items:");
Console.WriteLine();
foreach (var rec in salaryRecordsDict)
{
Console.WriteLine(rec);
}
Console.WriteLine();
}
// OfType
public void Linq47()
{
object[] numbers = { null, 1.0, "two", 3, "four", 5, "six", 7.0, 8, "nine" };
var strings = numbers.OfType<string>();
Console.WriteLine();
Console.WriteLine("Object Array: { null, 1.0, \"two\", 3, \"four\", 5, \"six\", 7.0, 8, \"nine\" }");
Console.WriteLine();
Console.WriteLine("Numbers stored as strings:");
Console.WriteLine();
foreach (var s in strings)
{
Console.WriteLine(s);
}
Console.WriteLine();
}
#endregion
#region Element Operators
// First - Simple
public void Linq48()
{
Employee emp = (from e in EmployeeList
select e).First();
Console.WriteLine();
Console.WriteLine("First Employee Record:");
Console.WriteLine();
Console.WriteLine(FormatEmployeeInformation(emp));
Console.WriteLine();
}
// First - Condition
public void Linq49()
{
Employee emp2011 = EmployeeList.First(e => e.DateOfJoining.Year == 2011);
Console.WriteLine();
Console.WriteLine("First Employee Record having Joining Year 2011:");
Console.WriteLine();
Console.WriteLine(FormatEmployeeInformation(emp2011));
Console.WriteLine();
}
// FirstOrDefault - Simple
public void Linq50()
{
int[] numbers = { };
int firstNumOrDefault = numbers.FirstOrDefault();
Console.WriteLine();
Console.WriteLine("Input Array: { }");
Console.WriteLine();
Console.WriteLine("First Record Or Default Record if First Not Available:");
Console.WriteLine();
Console.WriteLine(firstNumOrDefault);
Console.WriteLine();
}
// FirstOrDefault - Condition
public void Linq51()
{
var emp2002 = EmployeeList.FirstOrDefault(emp => emp.DateOfJoining.Year == 2002);
Console.WriteLine();
Console.WriteLine("First Record Or Default Record if First Not Available:");
Console.WriteLine();
Console.WriteLine("Any Employee Joined in the Year 2002: {0}", emp2002 != null);
Console.WriteLine();
}
// ElementAt
public void Linq52()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int fourthLowNum = (from n in numbers
where n > 5
select n).ElementAt(1);
// second number is index 1 because sequences use 0-based indexing
Console.WriteLine();
Console.WriteLine("Input Array: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("Second Number > 5: {0}", fourthLowNum);
Console.WriteLine();
}
#endregion
#region Generation Operators
// Range
public void Linq53()
{
var numbers = from n in Enumerable.Range(1, 10)
select new
{
Number = n,
OddEven = n % 2 == 1 ? "Odd" : "Even"
};
Console.WriteLine();
Console.WriteLine("Numbers from 1 to 10, identify Odd/Even");
Console.WriteLine();
foreach (var n in numbers)
{
Console.WriteLine("The Number {0} is {1}.", n.Number, n.OddEven);
}
Console.WriteLine();
}
// Repeat
public void Linq54()
{
var employees = Enumerable.Repeat<Employee>(EmployeeList.Last(), 5);
Console.WriteLine();
Console.WriteLine("Print Last Employee Record 5 times");
Console.WriteLine();
foreach (var e in employees)
{
Console.WriteLine(FormatEmployeeInformation(e));
}
Console.WriteLine();
}
#endregion
#region Quantifiers
// Any - Simple
public void Linq55()
{
bool nAfterA = EmployeeList.Any(emp => emp.Name.Contains("an"));
Console.WriteLine();
Console.WriteLine("There are employees whose name contains 'an': {0}", nAfterA);
Console.WriteLine();
}
// Any - Grouped
public void Linq56()
{
var deptGroups = from e in EmployeeList
group e by e.Department into g
where g.Any(e => e.DateOfJoining.Year == 2011)
select new
{
Dept = g.Key,
Employees = g
};
Console.WriteLine();
Console.WriteLine("List out the Departments which is having any of the employees under that department joined in 2011.");
Console.WriteLine();
foreach (var grp in deptGroups)
{
Console.WriteLine(grp.Dept);
}
Console.WriteLine();
}
// All - Simple
public void Linq57()
{
bool allSalLessThanOneLakh = EmployeeList.All(emp => emp.Salary < 100000);
Console.WriteLine();
Console.WriteLine("All the employees salaries are lesser than 100000: {0}", allSalLessThanOneLakh);
Console.WriteLine();
}
// All - Grouped
public void Linq58()
{
var deptGroups = from e in EmployeeList
group e by e.Department into g
where g.All(e => e.DateOfJoining.Year < 2009)
select new
{
Dept = g.Key,
Employees = g
};
Console.WriteLine();
Console.WriteLine("List out the Departments which is having all the employees under that department joined before 2009.");
Console.WriteLine();
foreach (var grp in deptGroups)
{
Console.WriteLine(grp.Dept);
}
Console.WriteLine();
}
#endregion
#region Aggregate Operators
// Count - Simple
public void Linq59()
{
int noOfEmployees = EmployeeList.Count();
Console.WriteLine();
Console.WriteLine("No of Employees: {0}", noOfEmployees.ToString());
Console.WriteLine();
}
// Count - Conditional
public void Linq60()
{
int noOfEmployeesSalMoreThan50000 = EmployeeList.Count(emp => emp.Salary > 50000);
Console.WriteLine();
Console.WriteLine("No of Employees having Salary more than 50000: {0}", noOfEmployeesSalMoreThan50000.ToString());
Console.WriteLine();
}
// Count - Grouped
public void Linq61()
{
var deptEmpCounts = from e in EmployeeList
group e by e.Department into g
select new
{
Department = g.Key,
EmpCount = g.Count()
};
Console.WriteLine();
Console.WriteLine("List of Departments with Employee Count in each Department:");
Console.WriteLine();
foreach (var dept in deptEmpCounts)
{
Console.WriteLine(dept.Department + ": " + dept.EmpCount.ToString());
}
Console.WriteLine();
}
// Sum - Simple
public void Linq62()
{
int sumOfNumbers1To50 = Enumerable.Range(1, 50).Sum();
Console.WriteLine();
Console.WriteLine("Sum of Numbers from 1 to 50: {0}", sumOfNumbers1To50);
Console.WriteLine();
}
// Sum - Projection
public void Linq63()
{
int sumOfOddNumbers1To50 = Enumerable.Range(1, 50).Sum(n => (n % 2 == 1) ? n : 0);
int sumOfEvenNumbers1To50 = Enumerable.Range(1, 50).Sum(n => (n % 2 == 0) ? n : 0);
Console.WriteLine();
Console.WriteLine("Sum of Odd Numbers from 1 to 50: {0}", sumOfOddNumbers1To50);
Console.WriteLine();
Console.WriteLine("Sum of Even Numbers from 1 to 50: {0}", sumOfEvenNumbers1To50);
Console.WriteLine();
}
// Sum - Grouped
public void Linq64()
{
var deptEmpSal = from e in EmployeeList
group e by e.Department into g
select new
{
Department = g.Key,
SumEmpSal = g.Sum(e => e.Salary)
};
Console.WriteLine();
Console.WriteLine("List of Departments with Sum of Employee Salaries:");
Console.WriteLine();
foreach (var dept in deptEmpSal)
{
Console.WriteLine(dept.Department + ": " + dept.SumEmpSal.ToString());
}
Console.WriteLine();
}
// Min/Max/Average - Simple
public void Linq65()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int minNum = numbers.Min();
int maxNum = numbers.Max();
double avg = numbers.Average();
Console.WriteLine();
Console.WriteLine("Input Array: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("The minimum number is {0}.", minNum);
Console.WriteLine("The maximum number is {0}.", maxNum);
Console.WriteLine("The Average is {0}.", avg);
Console.WriteLine();
}
// Min/Max/Average - Projection
public void Linq66()
{
double minSalary = EmployeeList.Min(emp => emp.Salary);
double maxSalary = EmployeeList.Max(emp => emp.Salary);
double avgSalary = EmployeeList.Average(emp => emp.Salary);
Console.WriteLine();
Console.WriteLine("Lowest Salary is: {0}", minSalary);
Console.WriteLine("Highest Salary is: {0}", maxSalary);
Console.WriteLine("Average Salary is: {0}", avgSalary);
Console.WriteLine();
}
// Min/Max/Average - Grouped
public void Linq67()
{
var deptEmpSals = from e in EmployeeList
group e by e.Department into g
select new
{
Department = g.Key,
MinSalary = g.Min(e => e.Salary),
MaxSalary = g.Max(e => e.Salary),
AvgSalary = g.Average(e => e.Salary)
};
Console.WriteLine();
Console.WriteLine("List of Departments with Lowest/Highest/Average Salaries:");
Console.WriteLine();
foreach (var dept in deptEmpSals)
{
Console.WriteLine(dept.Department + "\nMin Salary: " + dept.MinSalary.ToString() + "\nMax Salary: " + dept.MaxSalary.ToString() + "\nAvg Salary: " + dept.AvgSalary.ToString());
Console.WriteLine();
}
Console.WriteLine();
}
// Min/Max - Elements
public void Linq68()
{
var deptEmpSals = from e in EmployeeList
group e by e.Department into g
let maxSal = g.Max(e => e.Salary)
let minSal = g.Min(e => e.Salary)
select new
{
Department = g.Key,
LowestPaid = g.Where(e => e.Salary == minSal),
HighestPaid = g.Where(e => e.Salary == maxSal)
};
Console.WriteLine();
Console.WriteLine("List of Departments with Lowest/Highest Paid Employees:");
Console.WriteLine();
foreach (var dept in deptEmpSals)
{
Console.WriteLine(dept.Department);
Console.WriteLine("Lowest Paid:");
foreach (var lowestPaid in dept.LowestPaid)
{
Console.WriteLine(FormatEmployeeInformation(lowestPaid));
}
Console.WriteLine("Highest Paid:");
foreach (var highestPaid in dept.HighestPaid)
{
Console.WriteLine(FormatEmployeeInformation(highestPaid));
}
Console.WriteLine();
}
Console.WriteLine();
}
// Aggregate - Simple
public void Linq69()
{
double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9, 3.5, 8.9 };
double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);
Console.WriteLine();
Console.WriteLine("Input Doubles: { 1.7, 2.3, 1.9, 4.1, 2.9, 3.5, 8.9 }");
Console.WriteLine();
Console.WriteLine("Total Product of all numbers: {0}", product);
Console.WriteLine();
}
// Aggregate - Seed
public void Linq70()
{
double startBalance = 1000.0;
int[] attemptedWithdrawals = { 200, 100, 400, 500, 100, 700, 300 };
double endBalance = attemptedWithdrawals.Aggregate(startBalance, (balance, nextWithdrawal) =>
((nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance));
Console.WriteLine();
Console.WriteLine("Starting Balance: 1000.00");
Console.WriteLine();
Console.WriteLine("Attempted Withdrawals: { 200, 100, 400, 500, 100, 700, 300 }");
Console.WriteLine();
Console.WriteLine("Ending Balance: {0}", endBalance);
Console.WriteLine();
}
#endregion
#region Concat EqualAll Operators
// Concat - 1
public void Linq71()
{
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var allNumbers = numbersA.Concat(numbersB);
Console.WriteLine();
Console.WriteLine("Array 1: { 0, 2, 4, 5, 6, 8, 9 }");
Console.WriteLine("Array 2: { 1, 3, 5, 7, 8 }");
Console.WriteLine();
Console.WriteLine("All numbers from both arrays:");
foreach (var n in allNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
// Concat - 2
public void Linq72()
{
var keyWords = EmployeeList.Select(e => e.Name).Concat(EmployeeList.Select(e => e.Department));
Console.WriteLine();
Console.WriteLine("All Employees and Department Names:");
Console.WriteLine();
foreach (var n in keyWords)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
// SequenceEqual
public void Linq73()
{
var wordsA = new string[] { "microsoft", "adobe", "google" };
var wordsB = new string[] { "microsoft", "adobe", "google" };
bool match = wordsA.SequenceEqual(wordsB);
Console.WriteLine();
Console.WriteLine("Sequence 1: { \"microsoft\", \"adobe\", \"google\" }");
Console.WriteLine("Sequence 2: { \"microsoft\", \"adobe\", \"google\" }");
Console.WriteLine();
Console.WriteLine("The sequences match: {0}", match);
Console.WriteLine();
}
#endregion
#region Joins
// Cross Join
public void Linq74()
{
var deptCrossEmps = from d in DepartmentList
join e in EmployeeList on 1 equals 1
select new
{
Dept = d.Name,
EmployeeName = e.Name
};
Console.WriteLine();
Console.WriteLine("Department Cross Join Employee");
Console.WriteLine();
foreach (var deptEmp in deptCrossEmps)
{
Console.WriteLine(deptEmp.Dept + ": " + deptEmp.EmployeeName);
}
Console.WriteLine();
}
// Group/Inner Join
public void Linq75()
{
var deptEmps = from d in DepartmentList
join e in EmployeeList on d.Name equals e.Department
select new
{
Dept = d.Name,
EmployeeName = e.Name
};
Console.WriteLine();
Console.WriteLine("Department Group/Inner Join Employee");
Console.WriteLine();
foreach (var dept in deptEmps)
{
Console.WriteLine(dept.Dept + ": " + dept.EmployeeName);
}
Console.WriteLine();
}
// Left Outer Join
public void Linq76()
{
var deptEmps = from d in DepartmentList
join e in EmployeeList on d.Name equals e.Department into de
from e in de.DefaultIfEmpty()
select new
{
Department = d.Name,
EmpName = e == null ? "(No Employees Present)" : e.Name
};
Console.WriteLine();
Console.WriteLine("Department Left Outer Join Employee");
Console.WriteLine();
foreach (var dept in deptEmps)
{
Console.WriteLine(dept.Department + ": " + dept.EmpName);
}
Console.WriteLine();
}
#endregion
#region Query Execution
// Deferred Execution
public void Linq77()
{
// Sequence operators form first-class queries that are not executed until you enumerate over them.
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int i = 0;
var q = from n in numbers
select ++i;
// Note, the local variable 'i' is not incremented
// until each element is evaluated (as a side-effect):
Console.WriteLine();
Console.WriteLine("Deferred Execution");
Console.WriteLine();
foreach (var v in q)
{
Console.WriteLine("v = {0}, i = {1}", v, i);
}
Console.WriteLine();
}
// Immediate Execution
public void Linq78()
{
// Methods like ToList() cause the query to be executed immediately, caching the results.
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int i = 0;
var q = (from n in numbers
select ++i).ToList();
// The local variable i has already been fully // incremented before we iterate the results:
Console.WriteLine();
Console.WriteLine("Immediate Execution");
Console.WriteLine();
foreach (var v in q)
{
Console.WriteLine("v = {0}, i = {1}", v, i);
}
Console.WriteLine();
}
// Query Reuse
public void Linq79()
{
// Deferred execution lets us define a query once
// and then reuse it later after data changes.
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNumbers = from n in numbers
where n <= 3
select n;
Console.WriteLine();
Console.WriteLine("Numbers Array: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("First run numbers <= 3:");
Console.WriteLine();
foreach (int n in lowNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
for (int i = 0; i < 10; i++)
{
numbers[i] = -numbers[i];
}
// During this second run, the same query object,
// lowNumbers, will be iterating over the new state
// of numbers[], producing different results:
Console.WriteLine("Second run numbers <= 3:");
Console.WriteLine();
foreach (int n in lowNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
#endregion
}
}
Program.cs file (Code for calling LINQ Sample Methods) |
using System;
namespace CSharpSamples
{
class Program
{
static void Main()
{
LINQSamples objLinqSamples = new LINQSamples();
// Restriction Operators Begin
objLinqSamples.Linq1();
objLinqSamples.Linq2();
objLinqSamples.Linq3();
objLinqSamples.Linq4();
// Restriction Operators End
// Projection Operators Begin
objLinqSamples.Linq5();
objLinqSamples.Linq6();
objLinqSamples.Linq7();
objLinqSamples.Linq8();
objLinqSamples.Linq9();
objLinqSamples.Linq10();
objLinqSamples.Linq11();
objLinqSamples.Linq12();
objLinqSamples.Linq13();
objLinqSamples.Linq14();
objLinqSamples.Linq15();
// Projection Operators End
// Partitioning Operators Begin
objLinqSamples.Linq16();
objLinqSamples.Linq17();
objLinqSamples.Linq18();
objLinqSamples.Linq19();
objLinqSamples.Linq20();
objLinqSamples.Linq21();
// Partitioning Operators End
// Ordering Operators Begin
objLinqSamples.Linq22();
objLinqSamples.Linq23();
objLinqSamples.Linq24();
objLinqSamples.Linq25();
objLinqSamples.Linq26();
objLinqSamples.Linq27();
objLinqSamples.Linq28();
objLinqSamples.Linq29();
objLinqSamples.Linq30();
objLinqSamples.Linq31();
objLinqSamples.Linq32();
// Ordering Operators End
// Grouping Operators Begin
objLinqSamples.Linq33();
objLinqSamples.Linq34();
objLinqSamples.Linq35();
// Grouping Operators End
// Set Operators Begin
objLinqSamples.Linq36();
objLinqSamples.Linq37();
objLinqSamples.Linq38();
objLinqSamples.Linq39();
objLinqSamples.Linq40();
objLinqSamples.Linq41();
objLinqSamples.Linq42();
objLinqSamples.Linq43();
// Set Operators End
// Conversion Operators Begin
objLinqSamples.Linq44();
objLinqSamples.Linq45();
objLinqSamples.Linq46();
objLinqSamples.Linq47();
// Conversion Operators End
// Element Operators Begin
objLinqSamples.Linq48();
objLinqSamples.Linq49();
objLinqSamples.Linq50();
objLinqSamples.Linq51();
objLinqSamples.Linq52();
// Element Operators End
// Generation Operators Begin
objLinqSamples.Linq53();
objLinqSamples.Linq54();
// Generation Operators End
// Quantifiers Begin
objLinqSamples.Linq55();
objLinqSamples.Linq56();
objLinqSamples.Linq57();
objLinqSamples.Linq58();
// Quantifiers End
// Aggregate Operators Begin
objLinqSamples.Linq59();
objLinqSamples.Linq60();
objLinqSamples.Linq61();
objLinqSamples.Linq62();
objLinqSamples.Linq63();
objLinqSamples.Linq64();
objLinqSamples.Linq65();
objLinqSamples.Linq66();
objLinqSamples.Linq67();
objLinqSamples.Linq68();
objLinqSamples.Linq69();
objLinqSamples.Linq70();
// Aggregate Operators End
// Concat/SequenceEqual Operators Begin
objLinqSamples.Linq71();
objLinqSamples.Linq72();
objLinqSamples.Linq73();
// Concat/SequenceEqual Operators End
// Join Operators Begin
objLinqSamples.Linq74();
objLinqSamples.Linq75();
objLinqSamples.Linq76();
// Join Operators End
// Query Execution Begin
objLinqSamples.Linq77();
objLinqSamples.Linq78();
objLinqSamples.Linq79();
// Query Execution End
}
}
}
Where - Simple 1
This sample uses where to find all elements of an array less than 6.
public void Linq1()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums = from n in numbers
where n < 6
select n;
Console.WriteLine();
Console.WriteLine("Numers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("Numbers < 6:");
foreach (var x in lowNums)
{
Console.WriteLine(x);
}
Console.WriteLine();
}
Result
Numers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }
Numbers < 6:
5
4
1
3
2
0
Where - Simple 2
This sample uses where to find all employees having salary equals to 10000
public void Linq2()
{
var empWithSal10K = from e in EmployeeList
where e.Salary == 10000
select e;
Console.WriteLine();
Console.WriteLine("Employees having Salary equals to 10000:");
Console.WriteLine();
foreach (var emp in empWithSal10K)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
Result
Employees having Salary equals to 10000:
ID: 10 Name: Kumar Department: Admin Salary: 10000 DOJ: 08-Sep-2011
Where - Simple 3
This sample uses where to find all employees joined after 2009 and having salary more than 15000.
public void Linq3()
{
var employeesJoinedAfter2009WithMoreThan15K = from e in EmployeeList
where e.DateOfJoining > new DateTime(2009, 12, 31)
&& e.Salary > 15000
select e;
Console.WriteLine();
Console.WriteLine("Employees joined after 2009 and having salary more than 15000:");
Console.WriteLine();
foreach (var emp in employeesJoinedAfter2009WithMoreThan15K)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
Result
Employees joined after 2009 and having salary more than 15000:
ID: 4 Name: Praveen Department: Finance Salary: 22000 DOJ: 10-Feb-2010
ID: 7 Name: Avinash Department: Human Resources Salary: 32000 DOJ: 24-Mar-2011
Where - Indexed
This sample demonstrates an indexed Where clause that returns digits whose nameis shorter than their value.
public void Linq4()
{
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var shortDigits = digits.Where((digit, index) => digit.Length < index);
Console.WriteLine();
Console.WriteLine("Digits List: { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" }");
Console.WriteLine();
Console.WriteLine("Short digits:");
foreach (var d in shortDigits)
{
Console.WriteLine("The word {0} is shorter than its value.", d);
}
Console.WriteLine();
}
Digits List: { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }
Short digits:
The word five is shorter than its value.
The word six is shorter than its value.
The word seven is shorter than its value.
The word eight is shorter than its value.
The word nine is shorter than its value.
Select - Simple 1
This sample uses select to produce a sequence of ints one higher than those in anexisting array of ints.
public void Linq5()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numsPlusOne = from n in numbers
select n + 1;
Console.WriteLine();
Console.WriteLine("Numbers { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine("Numbers + 1:");
foreach (var i in numsPlusOne)
{
Console.WriteLine(i);
}
Console.WriteLine();
}
Result
Numbers + 1:
6
5
2
4
10
9
7
8
3
1
Select - Simple 2
This sample uses select to return a sequence of just the names of a list of employees.
public void Linq6()
{
var employeeNames = from e in EmployeeList
select e.Name;
Console.WriteLine();
Console.WriteLine("List of Employees:");
Console.WriteLine();
foreach (var empName in employeeNames)
{
Console.WriteLine(empName);
}
Console.WriteLine();
}
Result
of a sequence of ints.
List of Employees:
Anil
Prasad
Mohan
Praveen
Ravi
Krishna
Avinash
Pankaj
Narendra
Kumar
Select - Transformation
This sample uses select to produce a sequence of strings representing the text versionof a sequence of ints.
public void Linq7()
{
int[] numbers = { 4, 5, 1, 3, 9, 8, 6, 7, 2, 0 };
string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var textNums = from n in numbers
select strings[n];
Console.WriteLine();
Console.WriteLine("Numbers List: { 4, 5, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine("Strings List: { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" }");
Console.WriteLine();
Console.WriteLine("Number strings:");
foreach (var s in textNums)
{
Console.WriteLine(s);
}
Console.WriteLine();
}
Result
of each word in the original array.
Numbers List: { 4, 5, 1, 3, 9, 8, 6, 7, 2, 0 }
Strings List: { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }
Number strings:
four
five
one
three
nine
eight
six
seven
two
zero
Select - Anonymous Types 1
This sample uses select to produce a sequence of the uppercase and lowercase versionsof each word in the original array.
public void Linq8()
{
string[] words = { "MicroSOFT", "GooGle", "aDOBE", "aPPle" };
var upperLowerWords = from w in words
select new
{
Upper = w.ToUpper(),
Lower = w.ToLower()
};
Console.WriteLine();
Console.WriteLine("Input Words: { \"MicroSOFT\", \"GooGle\", \"aDOBE\", \"aPPle\" }");
Console.WriteLine();
foreach (var ul in upperLowerWords)
{
Console.WriteLine("UPPERCASE: {0}\t lowercase: {1}", ul.Upper, ul.Lower);
}
Console.WriteLine();
}
Result
and whether they are even or odd.
Input Words: { "MicroSOFT", "GooGle", "aDOBE", "aPPle" }
UPPERCASE: MICROSOFT lowercase: microsoft
UPPERCASE: GOOGLE lowercase: google
UPPERCASE: ADOBE lowercase: adobe
UPPERCASE: APPLE lowercase: apple
Select - Anonymous Types 2
This sample uses select to produce a sequence containing numbersand whether they are even or odd.
public void Linq9()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var digitOddEvens = from n in numbers
select new
{
Digit = strings[n],
Even = (n % 2 == 0)
};
Console.WriteLine();
Console.WriteLine("Even/Odd Check:");
Console.WriteLine();
foreach (var d in digitOddEvens)
{
Console.WriteLine("The digit {0} is {1}.", d.Digit, d.Even ? "even" : "odd");
}
Console.WriteLine();
}
Result
Even/Odd Check:
The digit five is odd.
The digit four is even.
The digit one is odd.
The digit three is odd.
The digit nine is odd.
The digit eight is even.
The digit six is even.
The digit seven is odd.
The digit two is even.
The digit zero is even.
Select - Anonymous Types 3
This sample uses select to Employees including Department and Salary.
public void Linq10()
{
var employeesInfo = from e in EmployeeList
select new
{
e.Name,
e.Department,
Salary = e.Salary
};
Console.WriteLine();
Console.WriteLine("Employees Info:");
Console.WriteLine();
foreach (var empInfo in employeesInfo)
{
Console.WriteLine("<{0}> is in the Department <{1}> and having salary <{2}>.", empInfo.Name, empInfo.Department, empInfo.Salary);
}
Console.WriteLine();
}
Result
array match their position in the array.
Employees Info:
<Anil> is in the Department <Information Technology> and having salary <20000>.
<Prasad> is in the Department <Information Technology> and having salary <25000>.
<Mohan> is in the Department <Information Technology> and having salary <50000>.
<Praveen> is in the Department <Finance> and having salary <22000>.
<Ravi> is in the Department <Finance> and having salary <40000>.
<Krishna> is in the Department <Human Resources> and having salary <80000>.
<Avinash> is in the Department <Human Resources> and having salary <32000>.
<Pankaj> is in the Department <Admin> and having salary <28000>.
<Narendra> is in the Department <Admin> and having salary <18000>.
<Kumar> is in the Department <Admin> and having salary <10000>.
Select - Indexed
This sample uses an indexed Select clause to determine if the value of ints in anarray match their position in the array.
public void Linq11()
{
int[] numbers = { 4, 5, 1, 3, 9, 8, 6, 7, 2, 0 };
var numsInPlace = numbers.Select((num, index) => new { Num = num, InPlace = (num == index) });
Console.WriteLine();
Console.WriteLine("Numbers List: { 4, 5, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("Number: In-Place?");
Console.WriteLine();
foreach (var n in numsInPlace)
{
Console.WriteLine("{0}: {1}", n.Num, n.InPlace);
}
Console.WriteLine();
}
Result
whose salary is more than 20000.
Numbers List: { 4, 5, 1, 3, 9, 8, 6, 7, 2, 0 }
Number: In-Place?
4: False
5: False
1: False
3: True
9: False
8: False
6: True
7: True
2: False
0: False
Select - Filtered
This sample combines select and where to make a simple query that returns the employeeswhose salary is more than 20000.
public void Linq12()
{
var employeesInfo = from e in EmployeeList
where e.Salary > 20000
select e;
Console.WriteLine();
Console.WriteLine("Employees having Salary > 20000:");
Console.WriteLine();
foreach (var emp in employeesInfo)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
Result
numbers from both arrays such that the number from numbersA is less than the number
from numbersB.
Employees having Salary > 20000:
ID: 2 Name: Prasad Department: Information Technology Salary: 25000 DOJ: 01-Dec-2005
ID: 3 Name: Mohan Department: Information Technology Salary: 50000 DOJ: 18-May-2003
ID: 4 Name: Praveen Department: Finance Salary: 22000 DOJ: 10-Feb-2010
ID: 5 Name: Ravi Department: Finance Salary: 40000 DOJ: 16-Jun-2007
ID: 6 Name: Krishna Department: Human Resources Salary: 80000 DOJ: 18-May-2003
ID: 7 Name: Avinash Department: Human Resources Salary: 32000 DOJ: 24-Mar-2011
ID: 8 Name: Pankaj Department: Admin Salary: 28000 DOJ: 09-Apr-2009
SelectMany - Compound from 1
This sample uses a compound from clause to make a query that returns all pairs ofnumbers from both arrays such that the number from numbersA is less than the number
from numbersB.
public void Linq13()
{
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var pairs = from a in numbersA
from b in numbersB
where a < b
select new { a, b };
Console.WriteLine();
Console.WriteLine("Set A: { 0, 2, 4, 5, 6, 8, 9 }");
Console.WriteLine("Set B: { 1, 3, 5, 7, 8 }");
Console.WriteLine();
Console.WriteLine("Pairs where a < b:");
Console.WriteLine();
foreach (var pair in pairs)
{
Console.WriteLine("{0} is less than {1}", pair.a, pair.b);
}
Console.WriteLine();
}
Result
is more than each salries list item.
Set A: { 0, 2, 4, 5, 6, 8, 9 }
Set B: { 1, 3, 5, 7, 8 }
Pairs where a < b:
0 is less than 1
0 is less than 3
0 is less than 5
0 is less than 7
0 is less than 8
2 is less than 3
2 is less than 5
2 is less than 7
2 is less than 8
4 is less than 5
4 is less than 7
4 is less than 8
5 is less than 7
5 is less than 8
6 is less than 7
6 is less than 8
SelectMany - Compound from 2
This sample uses a compound from clause to select all Employees where the employee salaryis more than each salries list item.
public void Linq14()
{
int[] salaries = { 10000, 15000, 20000, 25000 };
var empSalaries = from e in EmployeeList
from s in salaries
where e.Salary > s
select new
{
e.Name,
e.Salary,
s
};
Console.WriteLine();
Console.WriteLine("Salary Comparision with the Set: { 10000, 15000, 20000, 25000 }");
Console.WriteLine();
foreach (var item in empSalaries)
{
Console.WriteLine(item.Name + " Salary(" + item.Salary + ") is more than " + item.s.ToString());
}
Console.WriteLine();
}
Result
Salary Comparision with the Set: { 10000, 15000, 20000, 25000 }
Anil Salary(20000) is more than 10000
Anil Salary(20000) is more than 15000
Prasad Salary(25000) is more than 10000
Prasad Salary(25000) is more than 15000
Prasad Salary(25000) is more than 20000
Mohan Salary(50000) is more than 10000
Mohan Salary(50000) is more than 15000
Mohan Salary(50000) is more than 20000
Mohan Salary(50000) is more than 25000
Praveen Salary(22000) is more than 10000
Praveen Salary(22000) is more than 15000
Praveen Salary(22000) is more than 20000
Ravi Salary(40000) is more than 10000
Ravi Salary(40000) is more than 15000
Ravi Salary(40000) is more than 20000
Ravi Salary(40000) is more than 25000
Krishna Salary(80000) is more than 10000
Krishna Salary(80000) is more than 15000
Krishna Salary(80000) is more than 20000
Krishna Salary(80000) is more than 25000
Avinash Salary(32000) is more than 10000
Avinash Salary(32000) is more than 15000
Avinash Salary(32000) is more than 20000
Avinash Salary(32000) is more than 25000
Pankaj Salary(28000) is more than 10000
Pankaj Salary(28000) is more than 15000
Pankaj Salary(28000) is more than 20000
Pankaj Salary(28000) is more than 25000
Narendra Salary(18000) is more than 10000
Narendra Salary(18000) is more than 15000
SelectMany - Multiple from
This sample uses multiple from clauses so that filtering on employees can be donebefore selecting their selaries. This makes the query more efficient by not selecting
and then discarding salaries for employees whose name doesn't start with the letter "P".
public void Linq15()
{
int[] salaries = { 10000, 15000, 20000, 25000 };
var empSalaries = from e in EmployeeList
where e.Name.ToUpper().StartsWith("P")
from s in salaries
where e.Salary > s
select new
{
e.Name,
e.Salary,
s
};
Console.WriteLine();
Console.WriteLine("Salary Comparision of Employees whose names start with P with the Set: { 10000, 15000, 20000, 25000 }");
Console.WriteLine();
foreach (var item in empSalaries)
{
Console.WriteLine(item.Name + " Salary(" + item.Salary + ") is more than " + item.s.ToString());
}
Console.WriteLine();
}
Result
Salary Comparision of Employees whose names start with "P" with the Set: { 10000, 15000, 20000, 25000 }
Prasad Salary(25000) is more than 10000
Prasad Salary(25000) is more than 15000
Prasad Salary(25000) is more than 20000
Praveen Salary(22000) is more than 10000
Praveen Salary(22000) is more than 15000
Praveen Salary(22000) is more than 20000
Pankaj Salary(28000) is more than 10000
Pankaj Salary(28000) is more than 15000
Pankaj Salary(28000) is more than 20000
Pankaj Salary(28000) is more than 25000
Take - Simple
This sample uses Take to get only the first 4 elements of the array.
public void Linq16()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var first4Numbers = numbers.Take(4);
Console.WriteLine();
Console.WriteLine("Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("First 4 Numbers:");
Console.WriteLine();
foreach (var n in first4Numbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Result
Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }
First 4 Numbers:
5
4
1
3
TakeWhile - Simple
This sample uses TakeWhile to return elements starting from the beginning of thearray until a number is hit that is not less than 7.
public void Linq17()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var firstNumbersLessThan7 = numbers.TakeWhile(n => n < 7);
Console.WriteLine();
Console.WriteLine("Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("First Numbers less than 7:");
foreach (var n in firstNumbersLessThan7)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Result
array until a number is hit that is less than its position in the array.
Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }
First Numbers less than 7:
5
4
1
3
TakeWhile - Indexed
This sample uses TakeWhile to return elements starting from the beginning of thearray until a number is hit that is less than its position in the array.
public void Linq18()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index);
Console.WriteLine();
Console.WriteLine("Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("First numbers not less than their position:");
Console.WriteLine();
foreach (var n in firstSmallNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Result
Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }
First numbers not less than their position:
5
4
Skip - Simple
This sample uses Skip to get all but the first 3 elements of the array.
public void Linq19()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var allButFirst3Numbers = numbers.Skip(3);
Console.WriteLine();
Console.WriteLine("Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("All but first 3 numbers:");
Console.WriteLine();
foreach (var n in allButFirst3Numbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Result
element divisible by 2.Result
element less than its position.
Result
Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }
All but first 3 numbers:
3
9
8
6
7
2
0
SkipWhile - Simple
This sample uses SkipWhile to get the elements of the array starting from the firstelement divisible by 2.
public void Linq20()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0);
Console.WriteLine();
Console.WriteLine("Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("All elements starting from first element divisible by 3:");
Console.WriteLine();
foreach (var n in allButFirst3Numbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }
All elements starting from first element divisible by 3:
3
9
8
6
7
2
0
SkipWhile - Indexed
This sample uses SkipWhile to get the elements of the array starting from the firstelement less than its position.
public void Linq21()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var laterNumbers = numbers.SkipWhile((n, index) => n >= index);
Console.WriteLine();
Console.WriteLine("Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("All elements starting from first element greater than than its position:");
Console.WriteLine();
foreach (var n in laterNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Numbers List: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }
All elements starting from first element greater than than its position:
1
3
9
8
6
7
2
0
OrderBy - Simple 1
This sample uses orderby to sort a list of words alphabetically.
public void Linq22()
{
string[] words = { "Microsoft", "Google", "Adobe", "Apple", "IBM" };
var sortedWords = from w in words
orderby w
select w;
Console.WriteLine();
Console.WriteLine("Input Words: { \"Microsoft\", \"Google\", \"Adobe\", \"Apple\", \"IBM\" }");
Console.WriteLine();
Console.WriteLine("The sorted list of words:");
Console.WriteLine();
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
Console.WriteLine();
}
Input Words: { "Microsoft", "Google", "Adobe", "Apple", "IBM" }
The sorted list of words:
Adobe
Apple
Google
IBM
Microsoft
OrderBy - Simple 2
This sample uses orderby to sort a list of employees by name.
public void Linq23()
{
var sortedEmployees = from e in EmployeeList
orderby e.Name
select e;
Console.WriteLine();
Console.WriteLine("Employees List in Name Ascending Order:");
Console.WriteLine();
foreach (var emp in sortedEmployees)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
Employees List in Name Ascending Order:
ID: 1 Name: Anil Department: Information Technology Salary: 20000 DOJ: 11-Sep-2006
ID: 7 Name: Avinash Department: Human Resources Salary: 32000 DOJ: 24-Mar-2011
ID: 6 Name: Krishna Department: Human Resources Salary: 80000 DOJ: 18-May-2003
ID: 10 Name: Kumar Department: Admin Salary: 10000 DOJ: 08-Sep-2011
ID: 3 Name: Mohan Department: Information Technology Salary: 50000 DOJ: 18-May-2003
ID: 9 Name: Narendra Department: Admin Salary: 18000 DOJ: 19-Nov-2008
ID: 8 Name: Pankaj Department: Admin Salary: 28000 DOJ: 09-Apr-2009
ID: 2 Name: Prasad Department: Information Technology Salary: 25000 DOJ: 01-Dec-2005
ID: 4 Name: Praveen Department: Finance Salary: 22000 DOJ: 10-Feb-2010
ID: 5 Name: Ravi Department: Finance Salary: 40000 DOJ: 16-Jun-2007
OrderBy - Comparer
This sample uses an OrderBy clause with a custom comparer to do a case-insensitivesort of the words in an array.
public void Linq24()
{
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
var sortedWords = words.OrderBy(a => a, new CaseInsensitiveComparer());
Console.WriteLine();
Console.WriteLine("Input Words: { \"aPPLE\", \"AbAcUs\", \"bRaNcH\", \"BlUeBeRrY\", \"ClOvEr\", \"cHeRry\" }");
Console.WriteLine();
Console.WriteLine("The sorted(A-Z) list of words:");
Console.WriteLine();
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
Console.WriteLine();
}
Input Words: { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }
The sorted(A-Z) list of words:
AbAcUs
aPPLE
BlUeBeRrY
bRaNcH
cHeRry
ClOvEr
OrderByDescending - Simple 1
This sample uses orderby and descending to sort a list of doubles from highest tolowest.
public void Linq25()
{
double[] doubles = { 3.2, 1.3, 5.9, 7.1, 4.7 };
var sortedDoubles = from d in doubles
orderby d descending
select d;
Console.WriteLine();
Console.WriteLine("Input Decimals: { 3.2, 1.3, 5.9, 7.1, 4.7 }");
Console.WriteLine();
Console.WriteLine("The doubles from highest to lowest:");
Console.WriteLine();
foreach (var d in sortedDoubles)
{
Console.WriteLine(d);
}
Console.WriteLine();
}
Input Decimals: { 3.2, 1.3, 5.9, 7.1, 4.7 }
The doubles from highest to lowest:
7.1
5.9
4.7
3.2
1.3
OrderByDescending - Simple 2
This sample uses orderby to sort a list of emplouyees by salary from highestto lowest.
public void Linq26()
{
var sortedEmployees = from e in EmployeeList
orderby e.Salary descending
select e;
Console.WriteLine();
Console.WriteLine("Employees List from Highest to Lowest Salary:");
Console.WriteLine();
foreach (var emp in sortedEmployees)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
Employees List from Highest to Lowest Salary:
ID: 6 Name: Krishna Department: Human Resources Salary: 80000 DOJ: 18-May-2003
ID: 3 Name: Mohan Department: Information Technology Salary: 50000 DOJ: 18-May-2003
ID: 5 Name: Ravi Department: Finance Salary: 40000 DOJ: 16-Jun-2007
ID: 7 Name: Avinash Department: Human Resources Salary: 32000 DOJ: 24-Mar-2011
ID: 8 Name: Pankaj Department: Admin Salary: 28000 DOJ: 09-Apr-2009
ID: 2 Name: Prasad Department: Information Technology Salary: 25000 DOJ: 01-Dec-2005
ID: 4 Name: Praveen Department: Finance Salary: 22000 DOJ: 10-Feb-2010
ID: 1 Name: Anil Department: Information Technology Salary: 20000 DOJ: 11-Sep-2006
ID: 9 Name: Narendra Department: Admin Salary: 18000 DOJ: 19-Nov-2008
ID: 10 Name: Kumar Department: Admin Salary: 10000 DOJ: 08-Sep-2011
OrderByDescending - Comparer
This sample uses an OrderBy clause with a custom comparer to do a case-insensitivedescending sort of the words in an array.
public void Linq27()
{
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
var sortedWords = words.OrderByDescending(a => a, new CaseInsensitiveComparer());
Console.WriteLine();
Console.WriteLine("Input Words: { \"aPPLE\", \"AbAcUs\", \"bRaNcH\", \"BlUeBeRrY\", \"ClOvEr\", \"cHeRry\" }");
Console.WriteLine();
Console.WriteLine("The sorted(Z-A) list of words:");
Console.WriteLine();
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
Console.WriteLine();
}
Input Words: { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }
The sorted(Z-A) list of words:
ClOvEr
cHeRry
bRaNcH
BlUeBeRrY
aPPLE
AbAcUs
ThenBy - Simple
This sample uses a compound orderby to sort a list of digits, first by length oftheir name, and then alphabetically by the name itself.
public void Linq28()
{
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var sortedDigits = digits.OrderBy(d => d.Length).ThenBy(d => d);
Console.WriteLine();
Console.WriteLine("Input Words: { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" }");
Console.WriteLine();
Console.WriteLine("Sorted Words first by length and then by Alphabetical order:");
Console.WriteLine();
foreach (var d in sortedDigits)
{
Console.WriteLine(d);
}
Console.WriteLine();
}
Input Words: { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }
Sorted Words first by length and then by Alphabetical order:
one
six
two
five
four
nine
zero
eight
seven
three
ThenBy - Comparer
This sample uses an OrderBy and a ThenBy clause with a custom comparer to sort firstby word length and then by a case-insensitive sort of the words in an array.
public void Linq29()
{
string[] words = { "apple", "abacus", "branch", "blueberry", "clover", "cherry" };
var sortedWords = words.OrderBy(a => a.Length).ThenBy(a => a, new CaseInsensitiveComparer());
Console.WriteLine();
Console.WriteLine("Input Words: { \"apple\", \"abacus\", \"branch\", \"blueberry\", \"clover\", \"cherry\" }");
Console.WriteLine();
Console.WriteLine("The sorted list of words first by length and next by alphabetical order(A-Z):");
Console.WriteLine();
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
Console.WriteLine();
}
Input Words: { "apple", "abacus", "branch", "blueberry", "clover", "cherry" }
The sorted list of words first by length and next by alphabetical order(A-Z):
apple
abacus
branch
cherry
clover
blueberry
ThenByDescending - Simple
This sample uses a compound orderby to sort a list of products, first by category,and then by unit price, from highest to lowest.
public void Linq30()
{
var sortedEmployees = from e in EmployeeList
orderby e.Department, e.Salary descending
select e;
Console.WriteLine();
Console.WriteLine("Employees List in Department Ascending Order and Salary Descending Order:");
Console.WriteLine();
foreach (var emp in sortedEmployees)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
Employees List in Department Ascending Order and Salary Descending Order:
ID: 8 Name: Pankaj Department: Admin Salary: 28000 DOJ: 09-Apr-2009
ID: 9 Name: Narendra Department: Admin Salary: 18000 DOJ: 19-Nov-2008
ID: 10 Name: Kumar Department: Admin Salary: 10000 DOJ: 08-Sep-2011
ID: 5 Name: Ravi Department: Finance Salary: 40000 DOJ: 16-Jun-2007
ID: 4 Name: Praveen Department: Finance Salary: 22000 DOJ: 10-Feb-2010
ID: 6 Name: Krishna Department: Human Resources Salary: 80000 DOJ: 18-May-2003
ID: 7 Name: Avinash Department: Human Resources Salary: 32000 DOJ: 24-Mar-2011
ID: 3 Name: Mohan Department: Information Technology Salary: 50000 DOJ: 18-May-2003
ID: 2 Name: Prasad Department: Information Technology Salary: 25000 DOJ: 01-Dec-2005
ID: 1 Name: Anil Department: Information Technology Salary: 20000 DOJ: 11-Sep-2006
ThenByDescending - Comparer
This sample uses an OrderBy and a ThenBy clause with a custom comparer to sort firstby word length and then by a case-insensitive descending sort of the words in an
array.
public void Linq31()
{
string[] words = { "apple", "abacus", "branch", "blueberry", "clover", "cherry" };
var sortedWords = words.OrderBy(a => a.Length).ThenByDescending(a => a, new CaseInsensitiveComparer());
Console.WriteLine();
Console.WriteLine("Input Words: { \"apple\", \"abacus\", \"branch\", \"blueberry\", \"clover\", \"cherry\" }");
Console.WriteLine();
Console.WriteLine("The sorted list of words first by length ascending and next by alphabetical order descending(Z-A):");
Console.WriteLine();
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
Console.WriteLine();
}
Input Words: { "apple", "abacus", "branch", "blueberry", "clover", "cherry" }
The sorted list of words first by length ascending and next by alphabetical order descending(Z-A):
apple
clover
cherry
branch
abacus
blueberry
Reverse
This sample uses Reverse to create a list of all digits in the array whose secondletter is 'i' that is reversed from the order in the original array.
public void Linq32()
{
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var reversedIDigits = (from d in digits
where d[1] == 'i'
select d).Reverse();
Console.WriteLine();
Console.WriteLine("Input Words: { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" }");
Console.WriteLine();
Console.WriteLine("A backwards list of the digits with a second character of 'i':");
Console.WriteLine();
foreach (var d in reversedIDigits)
{
Console.WriteLine(d);
}
Console.WriteLine();
}
Input Words: { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }
A backwards list of the digits with a second character of 'i':
nine
eight
six
five
GroupBy - Simple 1
This sample uses group by to partition a list of numbers by their remainder whendivided by 5.
public void Linq33()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numberGroups = from n in numbers
group n by n % 4 into g
select new
{
Remainder = g.Key,
Numbers = g
};
Console.WriteLine();
Console.WriteLine("Input Numbers: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
foreach (var g in numberGroups)
{
Console.WriteLine("Numbers with a remainder of {0} when divided by 5:", g.Remainder);
foreach (var n in g.Numbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Console.WriteLine();
string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" };
var wordGroups = from w in words
group w by w[0] into g
select new
{
FirstLetter = g.Key,
Words = g
};
Console.WriteLine("Input Words: { \"blueberry\", \"chimpanzee\", \"abacus\", \"banana\", \"apple\", \"cheese\" }");
Console.WriteLine();
foreach (var g in wordGroups)
{
Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter);
foreach (var w in g.Words)
{
Console.WriteLine(w);
}
Console.WriteLine();
}
Console.WriteLine();
}
Result
Input Numbers: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }
Numbers with a remainder of 1 when divided by 5:
5
1
9
Numbers with a remainder of 0 when divided by 5:
4
8
0
Numbers with a remainder of 3 when divided by 5:
3
7
Numbers with a remainder of 2 when divided by 5:
6
2
Input Words: { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" }
Words that start with the letter 'b':
blueberry
banana
Words that start with the letter 'c':
chimpanzee
cheese
Words that start with the letter 'a':
abacus
apple
GroupBy - Simple 2
This sample uses group by to partition a list of employees by department.
public void Linq34()
{
var deptEmployees = from e in EmployeeList
group e by e.Department into Employees
select new
{
Department = Employees.Key,
Employees
};
Console.WriteLine();
Console.WriteLine("Departmentwise Employees List:");
Console.WriteLine();
foreach (var dept in deptEmployees)
{
Console.WriteLine("Department: " + dept.Department);
foreach (var emp in dept.Employees)
{
Console.WriteLine(FormatEmployeeInformation(emp));
}
Console.WriteLine();
}
Console.WriteLine();
}
Result
year, and then by month.
Departmentwise Employees List:
Department: Information Technology
ID: 1 Name: Anil Department: Information Technology Salary: 20000 DOJ: 11-Sep-2006
ID: 2 Name: Prasad Department: Information Technology Salary: 25000 DOJ: 01-Dec-2005
ID: 3 Name: Mohan Department: Information Technology Salary: 50000 DOJ: 18-May-2003
Department: Finance
ID: 4 Name: Praveen Department: Finance Salary: 22000 DOJ: 10-Feb-2010
ID: 5 Name: Ravi Department: Finance Salary: 40000 DOJ: 16-Jun-2007
Department: Human Resources
ID: 6 Name: Krishna Department: Human Resources Salary: 80000 DOJ: 18-May-2003
ID: 7 Name: Avinash Department: Human Resources Salary: 32000 DOJ: 24-Mar-2011
Department: Admin
ID: 8 Name: Pankaj Department: Admin Salary: 28000 DOJ: 09-Apr-2009
ID: 9 Name: Narendra Department: Admin Salary: 18000 DOJ: 19-Nov-2008
ID: 10 Name: Kumar Department: Admin Salary: 10000 DOJ: 08-Sep-2011
GroupBy - Nested
This sample uses group by to partition a list of each customer's orders, first byyear, and then by month.
public void Linq35()
{
var deptEmployees = from e in EmployeeList
group e by e.Department into DEPTGRPS
orderby DEPTGRPS.Key
select new
{
Dept = DEPTGRPS.Key,
DeptGroups = from e1 in DEPTGRPS
group e1 by e1.DateOfJoining.Year into YearGroups
orderby YearGroups.Key
select new
{
year = YearGroups.Key,
emps = YearGroups
}
};
Console.WriteLine();
Console.WriteLine("Department wise and joining year wise Employees List:");
Console.WriteLine();
foreach (var dept in deptEmployees)
{
Console.WriteLine("Department: " + dept.Dept);
foreach (var emp in dept.DeptGroups)
{
Console.WriteLine("Joining Year: " + emp.year.ToString());
foreach (var item in emp.emps)
{
Console.WriteLine(FormatEmployeeInformation(item));
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine();
}
Console.WriteLine();
}
Result
Department wise and joining year wise Employees List:
Department: Admin
Joining Year: 2008
ID: 9 Name: Narendra Department: Admin Salary: 18000 DOJ: 19-Nov-2008
Joining Year: 2009
ID: 8 Name: Pankaj Department: Admin Salary: 28000 DOJ: 09-Apr-2009
Joining Year: 2011
ID: 10 Name: Kumar Department: Admin Salary: 10000 DOJ: 08-Sep-2011
Department: Finance
Joining Year: 2007
ID: 5 Name: Ravi Department: Finance Salary: 40000 DOJ: 16-Jun-2007
Joining Year: 2010
ID: 4 Name: Praveen Department: Finance Salary: 22000 DOJ: 10-Feb-2010
Department: Human Resources
Joining Year: 2003
ID: 6 Name: Krishna Department: Human Resources Salary: 80000 DOJ: 18-May-2003
Joining Year: 2011
ID: 7 Name: Avinash Department: Human Resources Salary: 32000 DOJ: 24-Mar-2011
Department: Information Technology
Joining Year: 2003
ID: 3 Name: Mohan Department: Information Technology Salary: 50000 DOJ: 18-May-2003
Joining Year: 2005
ID: 2 Name: Prasad Department: Information Technology Salary: 25000 DOJ: 01-Dec-2005
Joining Year: 2006
ID: 1 Name: Anil Department: Information Technology Salary: 20000 DOJ: 11-Sep-2006
Distinct - 1
This sample uses Distinct to remove duplicate elements in a sequence of factorsof 300.
public void Linq36()
{
int[] factorsOf300 = { 2, 2, 3, 5, 5 };
var uniqueFactors = factorsOf300.Distinct();
Console.WriteLine();
Console.WriteLine("Prime factors of 300: { 2, 2, 3, 5, 5 }");
Console.WriteLine();
Console.WriteLine("Unique Prime factors of 300:");
Console.WriteLine();
foreach (var f in uniqueFactors)
{
Console.WriteLine(f);
}
Console.WriteLine();
}
Prime factors of 300: { 2, 2, 3, 5, 5 }
Unique Prime factors of 300:
2
3
5
Distinct - 2
This sample uses Distinct to find the unique Department names.
public void Linq37()
{
var departments = (from e in EmployeeList
select e.Department).Distinct();
Console.WriteLine();
Console.WriteLine("List of All Departments:");
Console.WriteLine();
foreach (var dept in departments)
{
Console.WriteLine(dept);
}
Console.WriteLine();
}
List of All Departments:
Information Technology
Finance
Human Resources
Admin
Union - 1
This sample uses Union to create one sequence that contains the unique values fromboth arrays.
public void Linq38()
{
int[] numbersA = { 0, 2, 4, 6, 8 };
int[] numbersB = { 0, 3, 6, 9 };
var uniqueNumbers = numbersA.Union(numbersB);
Console.WriteLine();
Console.WriteLine("Input Arrays: { 0, 2, 4, 6, 8 }, { 0, 3, 6, 9 }");
Console.WriteLine();
Console.WriteLine("Unique Numbers from both the arrays:");
Console.WriteLine();
foreach (var n in uniqueNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Input Arrays: { 0, 2, 4, 6, 8 }, { 0, 3, 6, 9 }
Unique Numbers from both the arrays:
0
2
4
6
8
3
9
Union - 2
This sample uses Union to create one sequence that contains the unique first letterfrom both employee and department names.
public void Linq39()
{
var empFirstChars = from e in EmployeeList
select e.Name[0];
var deptFirstChars = from e in EmployeeList
select e.Department[0];
var uniqueFirstChars = empFirstChars.Union(deptFirstChars);
Console.WriteLine();
Console.WriteLine("Unique first letters from Employee Names and Department Names:");
Console.WriteLine();
foreach (var ch in uniqueFirstChars)
{
Console.WriteLine(ch);
}
Console.WriteLine();
}
Unique first letters from Employee Names and Department Names:
A
P
M
R
K
N
I
F
H
Intersect - 1
This sample uses Intersect to create one sequence that contains the common valuesshared by both arrays.
public void Linq40()
{
int[] numbersA = { 0, 2, 4, 6, 8 };
int[] numbersB = { 0, 3, 6, 9 };
var commonNumbers = numbersA.Intersect(numbersB);
Console.WriteLine();
Console.WriteLine("Input Arrays: { 0, 2, 4, 6, 8 }, { 0, 3, 6, 9 }");
Console.WriteLine();
Console.WriteLine("Common Numbers from both the arrays:");
Console.WriteLine();
foreach (var n in commonNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Input Arrays: { 0, 2, 4, 6, 8 }, { 0, 3, 6, 9 }
Common Numbers from both the arrays:
0
6
Intersect - 2
This sample uses Intersect to create one sequence that contains the common firstletter from both employee and department names.
public void Linq41()
{
var empFirstChars = from e in EmployeeList
select e.Name[0];
var deptFirstChars = from e in EmployeeList
select e.Department[0];
var commonFirstChars = empFirstChars.Intersect(deptFirstChars);
Console.WriteLine();
Console.WriteLine("Common first letters from Employee Names and Department Names:");
Console.WriteLine();
foreach (var ch in commonFirstChars)
{
Console.WriteLine(ch);
}
Console.WriteLine();
}
Common first letters from Employee Names and Department Names:
A
Except - 1
This sample uses Except to create a sequence that contains the values from numbersA thatare not also in numbersB.
public void Linq42()
{
int[] numbersA = { 0, 2, 4, 6, 8 };
int[] numbersB = { 0, 3, 6, 9 };
var uniqueNumbers = numbersA.Except(numbersB);
Console.WriteLine();
Console.WriteLine("Input Arrays: { 0, 2, 4, 6, 8 }, { 0, 3, 6, 9 }");
Console.WriteLine();
Console.WriteLine("Numbers in first array but not in second array:");
Console.WriteLine();
foreach (var n in uniqueNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Input Arrays: { 0, 2, 4, 6, 8 }, { 0, 3, 6, 9 }
Numbers in first array but not in second array:
2
4
8
Except - 2
This sample uses Except to create one sequence that contains the first letters ofemployee names that are not first letters of department names.
public void Linq43()
{
var empFirstChars = from e in EmployeeList
select e.Name[0];
var deptFirstChars = from e in EmployeeList
select e.Department[0];
var commonFirstChars = empFirstChars.Except(deptFirstChars);
Console.WriteLine();
Console.WriteLine("First letters from Employee Names, but not from Department Names:");
Console.WriteLine();
foreach (var ch in commonFirstChars)
{
Console.WriteLine(ch);
}
Console.WriteLine();
}
First letters from Employee Names, but not from Department Names:
P
M
R
K
N
ToArray
This sample uses ToArray to immediately evaluate a sequence into an array.
public void Linq44()
{
double[] doubles = { 1.5, 2.3, 1.8, 4.2, 3.6, 5.4 };
var sortedDoubles = from d in doubles
orderby d descending
select d;
var doublesArray = sortedDoubles.ToArray();
Console.WriteLine();
Console.WriteLine("Array of Doubles: { 1.5, 2.3, 1.8, 4.2, 3.6, 5.4 }");
Console.WriteLine();
Console.WriteLine("Doubles from highest to lowest:");
Console.WriteLine();
for (int d = 0; d < doublesArray.Length; d++)
{
Console.WriteLine(doublesArray[d]);
}
Console.WriteLine();
}
Array of Doubles: { 1.5, 2.3, 1.8, 4.2, 3.6, 5.4 }
Doubles from highest to lowest:
5.4
4.2
3.6
2.3
1.8
1.5
ToList
This sample uses ToList to immediately evaluate Employee names into a List<T>.
public void Linq45()
{
var employees = from e in EmployeeList
orderby e.Department
select e.Name;
var empList = employees.ToList();
Console.WriteLine();
Console.WriteLine("The Sorted Employee List:");
Console.WriteLine();
foreach (var e in empList)
{
Console.WriteLine(e);
}
Console.WriteLine();
}
The Sorted Employee List:
Pankaj
Narendra
Kumar
Praveen
Ravi
Krishna
Avinash
Anil
Prasad
Mohan
ToDictionary
This sample uses ToDictionary to immediately evaluate a sequence and a related keyexpression into a dictionary.
public void Linq46()
{
var salaryRecords = new[]
{
new { Name = "Anil", Salary = 20000 },
new { Name = "Prasad" , Salary = 25000 },
new { Name = "Mohan", Salary = 50000 }
};
var salaryRecordsDict = salaryRecords.ToDictionary(sr => sr.Name);
Console.WriteLine();
Console.WriteLine("Salary Records: \n\n{ Name = \"Anil\", Salary = 20000 }\n{ Name = \"Prasad\" , Salary = 25000 }\n{ Name = \"Mohan\", Salary = 50000 }");
Console.WriteLine();
Console.WriteLine("Salary Records Dictionary Items:");
Console.WriteLine();
foreach (var rec in salaryRecordsDict)
{
Console.WriteLine(rec);
}
Console.WriteLine();
}
Salary Records:
{ Name = "Anil", Salary = 20000 }
{ Name = "Prasad" , Salary = 25000 }
{ Name = "Mohan", Salary = 50000 }
Salary Records Dictionary Items:
[Anil, { Name = Anil, Salary = 20000 }]
[Prasad, { Name = Prasad, Salary = 25000 }]
[Mohan, { Name = Mohan, Salary = 50000 }]
OfType
This sample uses OfType to return only the elements of the array that are of typestring.
public void Linq47()
{
object[] numbers = { null, 1.0, "two", 3, "four", 5, "six", 7.0, 8, "nine" };
var strings = numbers.OfType<string>();
Console.WriteLine();
Console.WriteLine("Object Array: { null, 1.0, \"two\", 3, \"four\", 5, \"six\", 7.0, 8, \"nine\" }");
Console.WriteLine();
Console.WriteLine("Numbers stored as strings:");
Console.WriteLine();
foreach (var s in strings)
{
Console.WriteLine(s);
}
Console.WriteLine();
}
Object Array: { null, 1.0, "two", 3, "four", 5, "six", 7.0, 8, "nine" }
Numbers stored as strings:
two
four
six
nine
First - Simple
This sample uses First to return the first matching element as an Employee , insteadof as a sequence containing an Employee.
public void Linq48()
{
Employee emp = (from e in EmployeeList
select e).First();
Console.WriteLine();
Console.WriteLine("First Employee Record:");
Console.WriteLine();
Console.WriteLine(FormatEmployeeInformation(emp));
Console.WriteLine();
}
First Employee Record:
ID: 1 Name: Anil Department: Information Technology Salary: 20000 DOJ: 11-Sep-2006
First - Condition
This sample uses First to find the first employee in the list joined in the year 2011.
public void Linq49()
{
Employee emp2011 = EmployeeList.First(e => e.DateOfJoining.Year == 2011);
Console.WriteLine();
Console.WriteLine("First Employee Record having Joining Year 2011:");
Console.WriteLine();
Console.WriteLine(FormatEmployeeInformation(emp2011));
Console.WriteLine();
}
First Employee Record having Joining Year 2011:
ID: 7 Name: Avinash Department: Human Resources Salary: 32000 DOJ: 24-Mar-2011
FirstOrDefault - Simple
This sample uses FirstOrDefault to try to return the first element of the sequence,unless there are no elements, in which case the default value for that type is returned.
public void Linq50()
{
int[] numbers = { };
int firstNumOrDefault = numbers.FirstOrDefault();
Console.WriteLine();
Console.WriteLine("Input Array: { }");
Console.WriteLine();
Console.WriteLine("First Record Or Default Record if First Not Available:");
Console.WriteLine();
Console.WriteLine(firstNumOrDefault);
Console.WriteLine();
}
Input Array: { }
First Record Or Default Record if First Not Available:
0
FirstOrDefault - Condition
This sample uses FirstOrDefault to return the first employee who joined in the year 2002as a single Employee object, unless there is no match, in which case null is returned.
public void Linq51()
{
var emp2002 = EmployeeList.FirstOrDefault(emp => emp.DateOfJoining.Year == 2002);
Console.WriteLine();
Console.WriteLine("First Record Or Default Record if First Not Available:");
Console.WriteLine();
Console.WriteLine("Any Employee Joined in the Year 2002: {0}", emp2002 != null);
Console.WriteLine();
}
First Record Or Default Record if First Not Available:
Any Employee Joined in the Year 2002: False
ElementAt
This sample uses ElementAt to retrieve the second number greater than 5 from anarray.
public void Linq52()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int fourthLowNum = (from n in numbers
where n > 5
select n).ElementAt(1);
// second number is index 1 because sequences use 0-based indexing
Console.WriteLine();
Console.WriteLine("Input Array: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("Second Number > 5: {0}", fourthLowNum);
Console.WriteLine();
}
Input Array: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }
Second Number > 5: 8
Range
This sample uses Range to generate a sequence of numbers from 1 to 10 that isused to find which numbers in that range are odd and even.
public void Linq53()
{
var numbers = from n in Enumerable.Range(1, 10)
select new
{
Number = n,
OddEven = n % 2 == 1 ? "Odd" : "Even"
};
Console.WriteLine();
Console.WriteLine("Numbers from 1 to 10, identify Odd/Even");
Console.WriteLine();
foreach (var n in numbers)
{
Console.WriteLine("The Number {0} is {1}.", n.Number, n.OddEven);
}
Console.WriteLine();
}
Numbers from 1 to 10, identify Odd/Even
The Number 1 is Odd.
The Number 2 is Even.
The Number 3 is Odd.
The Number 4 is Even.
The Number 5 is Odd.
The Number 6 is Even.
The Number 7 is Odd.
The Number 8 is Even.
The Number 9 is Odd.
The Number 10 is Even.
Repeat
This sample uses Repeat to generate a sequence that contains the last employee 5 times.
public void Linq54()
{
var employees = Enumerable.Repeat<Employee>(EmployeeList.Last(), 5);
Console.WriteLine();
Console.WriteLine("Print Last Employee Record 5 times");
Console.WriteLine();
foreach (var e in employees)
{
Console.WriteLine(FormatEmployeeInformation(e));
}
Console.WriteLine();
}
Print Last Employee Record 5 times
ID: 10 Name: Kumar Department: Admin Salary: 10000 DOJ: 08-Sep-2011
ID: 10 Name: Kumar Department: Admin Salary: 10000 DOJ: 08-Sep-2011
ID: 10 Name: Kumar Department: Admin Salary: 10000 DOJ: 08-Sep-2011
ID: 10 Name: Kumar Department: Admin Salary: 10000 DOJ: 08-Sep-2011
ID: 10 Name: Kumar Department: Admin Salary: 10000 DOJ: 08-Sep-2011
Any - Simple
This sample uses Any to determine if any of the employee names contain the substring'an'.
public void Linq55()
{
bool nAfterA = EmployeeList.Any(emp => emp.Name.Contains("an"));
Console.WriteLine();
Console.WriteLine("There are employees whose name contains 'an': {0}", nAfterA);
Console.WriteLine();
}
There are employees whose name contains 'an': True
Any - Grouped
This sample uses Any to return a department grouped list of Employees for the Departmentsthat have at least one employee joined in the year 2011.
public void Linq56()
{
var deptGroups = from e in EmployeeList
group e by e.Department into g
where g.Any(e => e.DateOfJoining.Year == 2011)
select new
{
Dept = g.Key,
Employees = g
};
Console.WriteLine();
Console.WriteLine("List out the Departments which is having any of the employees under that department joined in 2011.");
Console.WriteLine();
foreach (var grp in deptGroups)
{
Console.WriteLine(grp.Dept);
}
Console.WriteLine();
}
List out the Departments which is having any of the employees under that department joined in 2011.
Human Resources
Admin
All - Simple
This sample uses All to determine whether all the employees salraries are less than 100000.
public void Linq57()
{
bool allSalLessThanOneLakh = EmployeeList.All(emp => emp.Salary < 100000);
Console.WriteLine();
Console.WriteLine("All the employees salaries are lesser than 100000: {0}", allSalLessThanOneLakh);
Console.WriteLine();
}
All the employees salaries are lesser than 100000: True
All - Grouped
This sample uses All to return department grouped a list of employees for departmentsthat have all of their employees joined before 2009.
public void Linq58()
{
var deptGroups = from e in EmployeeList
group e by e.Department into g
where g.All(e => e.DateOfJoining.Year < 2009)
select new
{
Dept = g.Key,
Employees = g
};
Console.WriteLine();
Console.WriteLine("List out the Departments which is having all the employees under that department joined before 2009.");
Console.WriteLine();
foreach (var grp in deptGroups)
{
Console.WriteLine(grp.Dept);
}
Console.WriteLine();
}
List out the Departments which is having all the employees under that department joined before 2009.
Information Technology
Count - Simple
This sample uses Count to get the number of Employees.
public void Linq59()
{
int noOfEmployees = EmployeeList.Count();
Console.WriteLine();
Console.WriteLine("No of Employees: {0}", noOfEmployees.ToString());
Console.WriteLine();
}
No of Employees: 10
Count - Conditional
This sample uses Count to get the number of employees having salary is more than 50000.
public void Linq60()
{
int noOfEmployeesSalMoreThan50000 = EmployeeList.Count(emp => emp.Salary > 50000);
Console.WriteLine();
Console.WriteLine("No of Employees having Salary more than 50000: {0}", noOfEmployeesSalMoreThan50000.ToString());
Console.WriteLine();
}
No of Employees having Salary more than 50000: 1
Count - Grouped
This sample uses Count to return a list of departments and number of employees eachhas.
public void Linq61()
{
var deptEmpCounts = from e in EmployeeList
group e by e.Department into g
select new
{
Department = g.Key,
EmpCount = g.Count()
};
Console.WriteLine();
Console.WriteLine("List of Departments with Employee Count in each Department:");
Console.WriteLine();
foreach (var dept in deptEmpCounts)
{
Console.WriteLine(dept.Department + ": " + dept.EmpCount.ToString());
}
Console.WriteLine();
}
List of Departments with Employee Count in each Department:
Information Technology: 3
Finance: 2
Human Resources: 2
Admin: 3
Sum - Simple
This sample uses Sum to get the sum of the numbers from 1 to 50.
public void Linq62()
{
int sumOfNumbers1To50 = Enumerable.Range(1, 50).Sum();
Console.WriteLine();
Console.WriteLine("Sum of Numbers from 1 to 50: {0}", sumOfNumbers1To50);
Console.WriteLine();
}
Sum of Numbers from 1 to 50: 1275
Sum - Projection
This sample uses Sum to get the sum of Odd Numbers and Sum of Even Numbers from 1 to 50.
public void Linq63()
{
int sumOfOddNumbers1To50 = Enumerable.Range(1, 50).Sum(n => (n % 2 == 1) ? n : 0);
int sumOfEvenNumbers1To50 = Enumerable.Range(1, 50).Sum(n => (n % 2 == 0) ? n : 0);
Console.WriteLine();
Console.WriteLine("Sum of Odd Numbers from 1 to 50: {0}", sumOfOddNumbers1To50);
Console.WriteLine();
Console.WriteLine("Sum of Even Numbers from 1 to 50: {0}", sumOfEvenNumbers1To50);
Console.WriteLine();
}
Sum of Odd Numbers from 1 to 50: 625
Sum of Even Numbers from 1 to 50: 650
Sum - Grouped
This sample uses Sum to get the total employee salary for each Department.
public void Linq64()
{
var deptEmpSal = from e in EmployeeList
group e by e.Department into g
select new
{
Department = g.Key,
SumEmpSal = g.Sum(e=> e.Salary)
};
Console.WriteLine();
Console.WriteLine("List of Departments with Sum of Employee Salaries:");
Console.WriteLine();
foreach (var dept in deptEmpSal)
{
Console.WriteLine(dept.Department + ": " + dept.SumEmpSal.ToString());
}
Console.WriteLine();
}
List of Departments with Sum of Employee Salaries:
Information Technology: 95000
Finance: 62000
Human Resources: 112000
Admin: 56000
Min/Max/Average - Simple
This sample uses Min/Max/Average to get the lowest number in an array.
public void Linq65()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int minNum = numbers.Min();
int maxNum = numbers.Max();
double avg = numbers.Average();
Console.WriteLine();
Console.WriteLine("Input Array: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("The minimum number is {0}.", minNum);
Console.WriteLine("The maximum number is {0}.", maxNum);
Console.WriteLine("The Average is {0}.", avg);
Console.WriteLine();
}
Input Array: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }
The minimum number is 0.
The maximum number is 9.
The Average is 4.5.
Min/Max/Average - Projection
This sample uses Min/Max/Average to get the min/max/avg salaries among all the employees.
public void Linq66()
{
double minSalary = EmployeeList.Min(emp => emp.Salary);
double maxSalary = EmployeeList.Max(emp => emp.Salary);
double avgSalary = EmployeeList.Average(emp => emp.Salary);
Console.WriteLine();
Console.WriteLine("Lowest Salary is: {0}", minSalary);
Console.WriteLine("Highest Salary is: {0}", maxSalary);
Console.WriteLine("Average Salary is: {0}", avgSalary);
Console.WriteLine();
}
Lowest Salary is: 10000
Highest Salary is: 80000
Average Salary is: 32500
Min/Max/Average - Grouped
This sample uses Min/Max/Average to get the min/max/avg salary among each Department's Employees.
public void Linq67()
{
var deptEmpSals = from e in EmployeeList
group e by e.Department into g
select new
{
Department = g.Key,
MinSalary = g.Min(e => e.Salary),
MaxSalary = g.Max(e => e.Salary),
AvgSalary = g.Average(e => e.Salary)
};
Console.WriteLine();
Console.WriteLine("List of Departments with Lowest/Highest/Average Salaries:");
Console.WriteLine();
foreach (var dept in deptEmpSals)
{
Console.WriteLine(dept.Department + "\nMin Salary: " + dept.MinSalary.ToString() + "\nMax Salary: " + dept.MaxSalary.ToString() + "\nAvg Salary: " + dept.AvgSalary.ToString());
Console.WriteLine();
}
Console.WriteLine();
}
List of Departments with Lowest/Highest/Average Salaries:
Information Technology
Min Salary: 20000
Max Salary: 50000
Avg Salary: 31666.6666666667
Finance
Min Salary: 22000
Max Salary: 40000
Avg Salary: 31000
Human Resources
Min Salary: 32000
Max Salary: 80000
Avg Salary: 56000
Admin
Min Salary: 10000
Max Salary: 28000
Avg Salary: 18666.6666666667
Min/Max - Elements
This sample uses Min/Max to get the Employees with the Lowest/Highest paid in each department.
public void Linq68()
{
var deptEmpSals = from e in EmployeeList
group e by e.Department into g
let maxSal = g.Max(e => e.Salary)
let minSal = g.Min(e => e.Salary)
select new
{
Department = g.Key,
LowestPaid = g.Where(e => e.Salary == minSal),
HighestPaid = g.Where(e => e.Salary == maxSal)
};
Console.WriteLine();
Console.WriteLine("List of Departments with Lowest/Highest Paid Employees:");
Console.WriteLine();
foreach (var dept in deptEmpSals)
{
Console.WriteLine(dept.Department);
Console.WriteLine("Lowest Paid:");
foreach (var lowestPaid in dept.LowestPaid)
{
Console.WriteLine(FormatEmployeeInformation(lowestPaid));
}
Console.WriteLine("Highest Paid:");
foreach (var highestPaid in dept.HighestPaid)
{
Console.WriteLine(FormatEmployeeInformation(highestPaid));
}
Console.WriteLine();
}
Console.WriteLine();
}
List of Departments with Lowest/Highest Paid Employees:
Information Technology
Lowest Paid:
ID: 1 Name: Anil Department: Information Technology Salary: 20000 DOJ: 11-Sep-2006
Highest Paid:
ID: 3 Name: Mohan Department: Information Technology Salary: 50000 DOJ: 18-May-2003
Finance
Lowest Paid:
ID: 4 Name: Praveen Department: Finance Salary: 22000 DOJ: 10-Feb-2010
Highest Paid:
ID: 5 Name: Ravi Department: Finance Salary: 40000 DOJ: 16-Jun-2007
Human Resources
Lowest Paid:
ID: 7 Name: Avinash Department: Human Resources Salary: 32000 DOJ: 24-Mar-2011
Highest Paid:
ID: 6 Name: Krishna Department: Human Resources Salary: 80000 DOJ: 18-May-2003
Admin
Lowest Paid:
ID: 10 Name: Kumar Department: Admin Salary: 10000 DOJ: 08-Sep-2011
Highest Paid:
ID: 8 Name: Pankaj Department: Admin Salary: 28000 DOJ: 09-Apr-2009
Aggregate - Simple
This sample uses Aggregate to create a running product on the array that calculatesthe total product of all elements.
public void Linq69()
{
double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9, 3.5, 8.9 };
double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);
Console.WriteLine();
Console.WriteLine("Input Doubles: { 1.7, 2.3, 1.9, 4.1, 2.9, 3.5, 8.9 }");
Console.WriteLine();
Console.WriteLine("Total Product of all numbers: {0}", product);
Console.WriteLine();
}
Input Doubles: { 1.7, 2.3, 1.9, 4.1, 2.9, 3.5, 8.9 }
Total Product of all numbers: 2751.5047315
Aggregate - Seed
This sample uses Aggregate to create a running account balance that subtracts eachwithdrawal from the initial balance of 1000, as long as the balance never drops below
0
public void Linq70()
{
double startBalance = 1000.0;
int[] attemptedWithdrawals = { 200, 100, 400, 500, 100, 700, 300 };
double endBalance = attemptedWithdrawals.Aggregate(startBalance, (balance, nextWithdrawal) =>
((nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance));
Console.WriteLine();
Console.WriteLine("Starting Balance: 1000.00");
Console.WriteLine();
Console.WriteLine("Attempted Withdrawals: { 200, 100, 400, 500, 100, 700, 300 }");
Console.WriteLine();
Console.WriteLine("Ending Balance: {0}", endBalance);
Console.WriteLine();
}
Starting Balance: 1000.00
Attempted Withdrawals: { 200, 100, 400, 500, 100, 700, 300 }
Ending Balance: 200
Concat - 1
This sample uses Concat to create one sequence that contains each array's values,one after the other.
public void Linq71()
{
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var allNumbers = numbersA.Concat(numbersB);
Console.WriteLine();
Console.WriteLine("Array 1: { 0, 2, 4, 5, 6, 8, 9 }");
Console.WriteLine("Array 2: { 1, 3, 5, 7, 8 }");
Console.WriteLine();
Console.WriteLine("All numbers from both arrays:");
foreach (var n in allNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Result
and departments, including any duplicates.
Array 1: { 0, 2, 4, 5, 6, 8, 9 }
Array 2: { 1, 3, 5, 7, 8 }
All numbers from both arrays:
0
2
4
5
6
8
9
1
3
5
7
8
Concat - 2
This sample uses Concat to create one sequence that contains the names of all employeesand departments, including any duplicates.
public void Linq72()
{
var keyWords = EmployeeList.Select(e => e.Name).Concat(EmployeeList.Select(e => e.Department));
Console.WriteLine();
Console.WriteLine("All Employees and Department Names:");
Console.WriteLine();
foreach (var n in keyWords)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Result
order.
All Employees and Department Names:
Anil
Prasad
Mohan
Praveen
Ravi
Krishna
Avinash
Pankaj
Narendra
Kumar
Information Technology
Information Technology
Information Technology
Finance
Finance
Human Resources
Human Resources
Admin
Admin
Admin
SequenceEqual
This sample uses SequenceEqual to see if two sequences match on all elements in the sameorder.
public void Linq73()
{
var wordsA = new string[] { "microsoft", "adobe", "google" };
var wordsB = new string[] { "microsoft", "adobe", "google" };
bool match = wordsA.SequenceEqual(wordsB);
Console.WriteLine();
Console.WriteLine("Sequence 1: { \"microsoft\", \"adobe\", \"google\" }");
Console.WriteLine("Sequence 2: { \"microsoft\", \"adobe\", \"google\" }");
Console.WriteLine();
Console.WriteLine("The sequences match: {0}", match);
Console.WriteLine();
}
Sequence 1: { "microsoft", "adobe", "google" }
Sequence 2: { "microsoft", "adobe", "google" }
The sequences match: True
Cross Join
This sample shows how to efficiently join elements of two sequences.
public void Linq74()
{
var deptCrossEmps = from d in DepartmentList
join e in EmployeeList on 1 equals 1
select new
{
Dept = d.Name,
EmployeeName = e.Name
};
Console.WriteLine();
Console.WriteLine("Department Cross Join Employee");
Console.WriteLine();
foreach (var deptEmp in deptCrossEmps)
{
Console.WriteLine(deptEmp.Dept + ": " + deptEmp.EmployeeName);
}
Console.WriteLine();
}
Department Cross Join Employee
Admin: Anil
Admin: Prasad
Admin: Mohan
Admin: Praveen
Admin: Ravi
Admin: Krishna
Admin: Avinash
Admin: Pankaj
Admin: Narendra
Admin: Kumar
Finance: Anil
Finance: Prasad
Finance: Mohan
Finance: Praveen
Finance: Ravi
Finance: Krishna
Finance: Avinash
Finance: Pankaj
Finance: Narendra
Finance: Kumar
Human Resources: Anil
Human Resources: Prasad
Human Resources: Mohan
Human Resources: Praveen
Human Resources: Ravi
Human Resources: Krishna
Human Resources: Avinash
Human Resources: Pankaj
Human Resources: Narendra
Human Resources: Kumar
Information Technology: Anil
Information Technology: Prasad
Information Technology: Mohan
Information Technology: Praveen
Information Technology: Ravi
Information Technology: Krishna
Information Technology: Avinash
Information Technology: Pankaj
Information Technology: Narendra
Information Technology: Kumar
Sales: Anil
Sales: Prasad
Sales: Mohan
Sales: Praveen
Sales: Ravi
Sales: Krishna
Sales: Avinash
Sales: Pankaj
Sales: Narendra
Sales: Kumar
Group/Inner Join
Using a group/inner join you can get all the Employees that match a given Department bundledas a sequence.
public void Linq75()
{
var deptEmps = from d in DepartmentList
join e in EmployeeList on d.Name equals e.Department
select new
{
Dept = d.Name,
EmployeeName = e.Name
};
Console.WriteLine();
Console.WriteLine("Department Group/Inner Join Employee");
Console.WriteLine();
foreach (var dept in deptEmps)
{
Console.WriteLine(dept.Dept + ": " + dept.EmployeeName);
}
Console.WriteLine();
}
Department Group/Inner Join Employee
Admin: Pankaj
Admin: Narendra
Admin: Kumar
Finance: Praveen
Finance: Ravi
Human Resources: Krishna
Human Resources: Avinash
Information Technology: Anil
Information Technology: Prasad
Information Technology: Mohan
Left Outer Join
A so-called outer join can be expressed with a group join. A left outer join is likea cross join, except that all the left hand side elements get included at least
once, even if they don't match any right hand side elements. Note how Sales Department shows
up in the output even though it has no employees.
public void Linq76()
{
var deptEmps = from d in DepartmentList
join e in EmployeeList on d.Name equals e.Department into de
from e in de.DefaultIfEmpty()
select new
{
Department = d.Name,
EmpName = e == null ? "(No Employees Present)" : e.Name
};
Console.WriteLine();
Console.WriteLine("Department Left Outer Join Employee");
Console.WriteLine();
foreach (var dept in deptEmps)
{
Console.WriteLine(dept.Department + ": " + dept.EmpName);
}
Console.WriteLine();
}
Department Left Outer Join Employee
Admin: Pankaj
Admin: Narendra
Admin: Kumar
Finance: Praveen
Finance: Ravi
Human Resources: Krishna
Human Resources: Avinash
Information Technology: Anil
Information Technology: Prasad
Information Technology: Mohan
Sales: (No Employees Present)
Deferred Execution
The following sample shows how query execution is deferred until the query is enumeratedat a foreach statement.
public void Linq77()
{
// Sequence operators form first-class queries that are not executed until you enumerate over them.
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int i = 0;
var q = from n in numbers
select ++i;
// Note, the local variable 'i' is not incremented
// until each element is evaluated (as a side-effect):
Console.WriteLine();
Console.WriteLine("Deferred Execution");
Console.WriteLine();
foreach (var v in q)
{
Console.WriteLine("v = {0}, i = {1}", v, i);
}
Console.WriteLine();
}
Result
such as ToList().
Deferred Execution
v = 1, i = 1
v = 2, i = 2
v = 3, i = 3
v = 4, i = 4
v = 5, i = 5
v = 6, i = 6
v = 7, i = 7
v = 8, i = 8
v = 9, i = 9
v = 10, i = 10
Immediate Execution
The following sample shows how queries can be executed immediately with operatorssuch as ToList().
public void Linq78()
{
// Methods like ToList() cause the query to be executed immediately, caching the results.
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int i = 0;
var q = (from n in numbers
select ++i).ToList();
// The local variable i has already been fully // incremented before we iterate the results:
Console.WriteLine();
Console.WriteLine("Immediate Execution");
Console.WriteLine();
foreach (var v in q)
{
Console.WriteLine("v = {0}, i = {1}", v, i);
}
Console.WriteLine();
}
Result
again after data changes and will then operate on the new data.
Immediate Execution
v = 1, i = 10
v = 2, i = 10
v = 3, i = 10
v = 4, i = 10
v = 5, i = 10
v = 6, i = 10
v = 7, i = 10
v = 8, i = 10
v = 9, i = 10
v = 10, i = 10
Query Reuse
The following sample shows how, because of deferred execution, queries can be usedagain after data changes and will then operate on the new data.
public void Linq79()
{
// Deferred execution lets us define a query once
// and then reuse it later after data changes.
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNumbers = from n in numbers
where n <= 3
select n;
Console.WriteLine();
Console.WriteLine("Numbers Array: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }");
Console.WriteLine();
Console.WriteLine("First run numbers <= 3:");
Console.WriteLine();
foreach (int n in lowNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
for (int i = 0; i < 10; i++)
{
numbers[i] = -numbers[i];
}
// During this second run, the same query object,
// lowNumbers, will be iterating over the new state
// of numbers[], producing different results:
Console.WriteLine("Second run numbers <= 3:");
Console.WriteLine();
foreach (int n in lowNumbers)
{
Console.WriteLine(n);
}
Console.WriteLine();
}
Numbers Array: { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }
First run numbers <= 3:
1
3
2
0
Second run numbers <= 3:
-5
-4
-1
-3
-9
-8
-6
-7
-2
0
LINQ techiniques are broadly covered in the above examples with results with sample data. Provide your comments/suggestions for further improvement.