Sie sind auf Seite 1von 22

1

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

1. Introduction
2. Motivation
3. Lambda expressions
4. LINQ
5. References
6. Q + maybe A

LINQ
Language Integrated
Query
Adds native data querying
abilities to .NET
Resembles SQL
High level -> performance
overhead
eg:

var CoolPeople = from p in


people where p.CoolFactor > 9
select new { name = p.FirstName
+ ' ' + p.LastName };

Lambda expressions

Mathematically based on lambda


calculus
Functional programming
Anonymous functions: defining
functions without bounding to
indentifier
Example:
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7,
2, 0 };
int oddNumbers = numbers.Count(n
=> n % 2 == 1);

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

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

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);

delegate int del(int i);


static void Main(string[] args)
{
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}

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

Supports ~all the same as SQL


Can be used WITH lambda
Providers
o
o
o
o

LINQ to objects
LINQ to XML
LINQ to SQL
LINQ to Sharepoint

10

Select
Where
SelectMany
Sum / Min / Max / Average
Aggregate
Join / GroupJoin
Take / TakeWhile
Skip / SkipWhile
OfType
Concat
OrderBy / ThenBy

Reverse
GroupBy
Distinct
Union / Intersect / Except
SequenceEqual
First / FirstOrDefault / Last
/ LastOrDefault
Single
ElementAt
Any / All / Contains
Count

11

1. Normal syntax
2. Lambda syntax
3. Where
4. Select
5. Order
6. Grouping
7. Set operators
8. Aggregate functions
9. Joins

12

SQL-like syntax
var productInfos =
from p in products
select p;

13

Lambda syntax:
customers.Where(c => c.City == "London");

14

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

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

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

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

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

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

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

Good reference:
http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

22

Das könnte Ihnen auch gefallen