Public · Protected · Private
Sample LINQ queries
Type: Public  |  Created: 2012-05-17  |  Frozen: Yes
« Previous Public Blog Next Public Blog »
Comments
  • string[] allProducts = { "car", "bike", "jeep", "taxi", "truck" }; int[] allNumbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; // as is var asis = from p in allProducts select p; foreach (var a in asis) { Console.WriteLine(a.ToString()); } //where var biggerOnes = from p in allNumbers where p > 10 select p; foreach (var a in biggerOnes) { Console.WriteLine(a.ToString()); } // Get count int numb = (from g in allNumbers where g > 6 select g).Count<int>(); Console.WriteLine(numb.ToString()); //Reverse order var allinreverse = (from p in allProducts select p).Reverse(); foreach (var prod in allinreverse) { Console.WriteLine(prod.ToString()); } // alphabetic sort. var sorteProducts = from p in allProducts orderby p select p; foreach (var p in sorteProducts) { Console.WriteLine(p); } // Dealing Two Lists List<string> firstList = new List<String> { "car", "bike", "truck" }; List<string> secondList = new List<String> { "truck", "jeep", "tractor" }; // Intersect (commonstuff) var commonStuff = (from c in firstList select c).Intersect (from c2 in secondList select c2); foreach (string s in commonStuff) Console.WriteLine(s); var allUnion = (from c in firstList select c).Union (from c2 in secondList select c2); foreach (string s in allUnion) Console.WriteLine(s); var carConcat = (from c in firstList select c).Concat (from c2 in secondList select c2); foreach (string s in carConcat) Console.WriteLine(s); var distinctList = ((from c in firstList select c).Concat (from c2 in secondList select c2)).Distinct(); foreach (string s in distinctList) Console.WriteLine(s); //Dealing with Aggregations Console.WriteLine("Max: {0}", (from t in allNumbers select t).Max()); Console.WriteLine("Min {0}", (from t in allNumbers select t).Min()); Console.WriteLine("Avg: {0}", (from t in allNumbers select t).Average()); Console.WriteLine("Sum: {0}", (from t in allNumbers select t).Sum());
    2012-05-17 05:08
This blog is frozen. No new comments or edits allowed.