1 / 22

Lambda and LINQ in C#

The fancy stuff. Lambda and LINQ in C#. Purpose of these slides. Direct the flow of the presentation AND Serve as a place for you to check details on LINQ stuff "I remember join was possible but can't remember the details.." These two are equally important. Summary. Introduction

alma
Download Presentation

Lambda and LINQ in C#

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. The fancy stuff Lambda and LINQ in C#

  2. Purpose of these slides • Direct the flow of the presentation AND • Serve as a place for you to check details on LINQ stuff • "I remember join was possible but can't remember the details.." These two are equally important

  3. Summary • Introduction • Motivation • Lambda expressions • LINQ • References • Q + maybe A

  4. 1. Introduction 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);

  5. 2. Motivation • Why learn to use new ways to program when I already know how to do things in a old way?? • Productivity • Readability • 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

  6. 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

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

  8. 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 }

  9. 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");

  10. 4. LINQ / 1 • Supports ~all the same as SQL • Can be used WITH lambda • Providers • LINQ to objects • LINQ to XML • LINQ to SQL • LINQ to Sharepoint

  11. LINQ / 2 supports (according to Wikipedia) • 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

  12. LINQ - Features • Normal syntax • Lambda syntax • Where • Select • Order • Grouping • Set operators •  Aggregate functions •  Joins

  13. LINQ example 1 SQL-like syntax  var productInfos =         from p in products         select p;

  14. LINQ example 2 Lambda syntax: customers.Where(c => c.City == "London"); You can group expressions. Order: rightmost is most important customers.Where(c => c.Sex == "female").Where(c => c.Age > 20 && c.Age > 16).OrderBy(c => c.FirstName).OrderBy(c => c.LastName);

  15. 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);     } }

  16. 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");     } }

  17. 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); } } }

  18. 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); } } }

  19. 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); } }

  20. 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); }

  21. 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);             }

  22. In the horizon Good reference: http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

More Related