Lambda and LINQ in C#
1
Purpose of these slides
• Direct the flow of the presentation
AND
• Serve as a place for you to check details on LINQ stuff
o "I remember join was possible but can't remember the
details.."
These two are equally important
2
Summary
1. Introduction
2. Motivation
3. Lambda expressions
4. LINQ
5. References
6. Q + maybe A
3
1. Introduction
LINQ Lambda expressions
• Language Integrated • Mathematically based on lambda
calculus
Query • Functional programming
• Adds native data querying • Anonymous functions: defining
abilities to .NET functions without bounding to
• Resembles SQL indentifier
• High level -> performance
Example:
overhead
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7,
eg: 2, 0 };
int oddNumbers = numbers.Count(n
var CoolPeople = from p in => n % 2 == 1);
people where p.CoolFactor > 9
select new { name = p.FirstName
+ ' ' + p.LastName };
4
2. Motivation
• Why learn to use new ways to program when I already know
how to do things in a old way??
o Productivity
o Readability
o In a long run, the results will be better
even though NOW you will be more productive
programming in old Java way
Lambda: Why is this cool? It allows you to write quick throw
away functions without naming them.
• 1 row of LINQ can save you from writing 3 nested loops
• 1 row of Lambda stuff can save you from writing 2 new
methods
5
3. Lambda / 1
• Anonymous functions
• Can be used in fancy ways
• ...But in reality (also called: this project) you will most likely
use lambda expressions as parameters to LINQ
6
3. Lambda / 2
• Expression lambdas
(int x, string s) => s.Length > x
• Statement lambdas
delegate void TestDelegate(string s);
…
TestDelegate myDel = n => { string s = n + " " + "World";
Console.WriteLine(s); };
myDel("Hello");
• Lambdas with standard query operators
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);
7
3. Lambda / 3, example 1
delegate int del(int i);
static void Main(string[] args)
{
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}
8
3. Lambda / 4, example 2
Assigning delegate
// c# 2.0
employee.SalaryChanged += delegate(Employee sender,
double amount)
{
Console.Writeline("changed");
}
// c# 3.0
employee.SalaryChanged += (sender, amount) =>
Console.Writeline("changed");
9
4. LINQ / 1
• Supports ~all the same as SQL
• Can be used WITH lambda
• Providers
o LINQ to objects
o LINQ to XML
o LINQ to SQL
o LINQ to Sharepoint
10
LINQ / 2 supports (according to
Wikipedia)
• Select • Reverse
• Where • GroupBy
• SelectMany • Distinct
• Sum / Min / Max / Average • Union / Intersect / Except
• Aggregate • SequenceEqual
• Join / GroupJoin • First / FirstOrDefault /
• Take / TakeWhile Last / LastOrDefault
• Skip / SkipWhile • Single
• OfType • ElementAt
• Concat • Any / All / Contains
• OrderBy / ThenBy • Count
11
LINQ - Features
1. Normal syntax
2. Lambda syntax
3. Where
4. Select
5. Order
6. Grouping
7. Set operators
8. Aggregate functions
9. Joins
12
LINQ example 1
SQL-like syntax
var productInfos =
from p in products
select p;
13
LINQ example 2
Lambda syntax:
customers.Where(c => c.City == "London");
14
Where
public void Linq5()
{
string[] digits = { "zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine" };
var shortDigits = digits.Where((digit, index) => digit.Length < index);
Console.WriteLine("Short digits:");
foreach (var d in shortDigits)
{
Console.WriteLine("The word {0} is shorter than its value.", d);
}
}
15
Select
public void Linq10()
{
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].ToUpper(), Even = (n % 2 == 0) };
foreach (var d in digitOddEvens)
{
Console.WriteLine("The digit {0} is {1}.", d.Digit, d.Even ? "even" : "odd");
}
}
16
Order
public class CaseInsensitiveComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return string.Compare(x, y, StringComparison.OrdinalIgnoreCase);
}
}
class Program
{
public static void Linq31() {
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
var sortedWords = words.OrderBy(a => a, new CaseInsensitiveComparer());
foreach (var word in sortedWords)
{
Console.WriteLine(word);
}
}
17
Grouping
public static void Linq41()
{
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 };
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);
}
}
}
18
Set operators
Distinct, union, intersect, except
public static void Linq46()
{
int[] factorsOf300 = { 2, 2, 3, 5, 5 };
var uniqueFactors = factorsOf300.Distinct();
Console.WriteLine("Prime factors of 300:");
foreach (var f in uniqueFactors)
{
Console.WriteLine(f);
}
}
19
Aggregate functions
Count, min, max, sum, average
public void Linq79()
{
string[] words = { "cherry", "apple", "blueberry" };
double totalChars = words.Sum(w => w.Length);
Console.WriteLine("There are a total of {0} characters in these words.",
totalChars);
}
20
Joins
System.Collections.Generic.Dictionary<int, string> names = new
Dictionary<int,string>();
names.Add(1, "Panu");
names.Add(2, "Jeesus");
System.Collections.Generic.Dictionary<int, string> addresses = new
Dictionary<int,string>();
addresses.Add(1, "Panu");
addresses.Add(2, "Jeesus");
var addressbook =
from n in names
join a in addresses on n.Key equals a.Key
select new { Name = n.Value, Address = a.Value };
foreach (var v in addressbook)
{
Console.WriteLine(v.Address + ": " + v.Name);
}
21
In the horizon
Good reference:
http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
22