LINQ表达式总结笔记
Lambda表达式的写法 ArgumentsToProcess => StatementsToProcessThem 小试牛刀一把,看看LAMDA表达式的威力. List<int> list = new List<int>() { 2, 3, 4, 5, 8 }; List<int> evenNumbers = list.FindAll(i => (i % 2) == 0); foreach (int even in evenNumbers) { Console.WriteLine(even); }
1. Where子句条件过滤结果集型(集合数据使用这种,譬如数组、列表数据,同样适用于Datatable等多列数据集) 类SQL语句的写法,对集合进行运算; int[] factorsOf300 = { 2, 2, 3, 5, 5 }; var filters = from p in factorsOf300 where p<5 select p; foreach (var filter in filters) { Console.WriteLine("Value: " + Convert.ToString(filter)); }
2. 对数据集进行函数运算型(特别注意select方法里面需要用new关键字来确定记录子集合) string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" }; var upperLowerWords = from w in words select new { Upper = w.ToUpper(), Lower = w.ToLower() }; foreach (var ul in upperLowerWords) { Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower); }
3. 多个数据子集进行复合计算: 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("Pairs where a < b:"); foreach (var pair in pairs) { Console.WriteLine("{0} is less than {1}", pair.a, pair.b); }
4. 子集运算,其中常见的算符有 Take, Skip, TakeWhile, SkipWhile. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var first3Numbers = numbers.Take(3);
Console.WriteLine("First 3 numbers:"); foreach (var n in first3Numbers) { Console.WriteLine(n); }
5. 排序运算, double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; var sortedDoubles = from d in doubles orderby d descending select d;
Console.WriteLine("The doubles from highest to lowest:"); foreach (var d in sortedDoubles) { Console.WriteLine(d); }
6. 分组运算 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); } }
7. 集合运算,算符包括Distinct, Union, Intersect, Except。 int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var uniqueNumbers = numbersA.Union(numbersB);
Console.WriteLine("Unique numbers from both arrays:"); foreach (var n in uniqueNumbers) { Console.WriteLine(n); } 此集合输出为进行整合过后的一个数据集;
8. 转换操作,主要是包含 ToArray, ToList, ToDictionary, OfType这几个操作指令。 double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; var sortedDoubles = from d in doubles orderby d descending select d; var doublesArray = sortedDoubles.ToArray();
Console.WriteLine("Every other double from highest to lowest:"); for (int d = 0; d < doublesArray.Length; d += 2) { Console.WriteLine(doublesArray[d]); }
9. 元素操作: -- First - Simple -- First - Condition -- FirstOrDefault - Simple -- FirstOrDefault - Condition -- ElementAt string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; string startsWithO = strings.First(s => s[0] == 'o');
10. 子序列生成功能: Range功能: var numbers = from n in Enumerable.Range(100, 50) select new { Number = n, OddEven = n % 2 == 1 ? "odd" : "even" }; foreach (var n in numbers) { Console.WriteLine("The number {0} is {1}.", n.Number, n.OddEven); } Repeat功能: var numbers = Enumerable.Repeat(7, 10); foreach (var n in numbers) { Console.WriteLine(n); }
11.集合筛选判断功能: -- Any - Simple -- Any - Grouped -- All - Simple -- All - Grouped - Any - Simple string[] words = { "believe", "relief", "receipt", "field" }; bool iAfterE = words.Any(w => w.Contains("ei"));
-- Any - Grouped功能: List<Product> products = GetProductList(); var productGroups = from p in products group p by p.Category into g where g.Any(p => p.UnitsInStock == 0) select new { Category = g.Key, Products = g };
12.数据集的聚合功能: Count, Sum, Min, Max, Average, Aggregate函数 int[] factorsOf300 = { 2, 2, 3, 5, 5 }; int uniqueFactors = factorsOf300.Distinct().Count();
13.集合叠加以及顺序比较功能: Concat,EqualAll函数 int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var allNumbers = numbersA.Concat(numbersB);
14.自定义函数功能: int[] vectorA = { 0, 2, 4, 5, 6 }; int[] vectorB = { 1, 3, 5, 7, 8 }; int dotProduct = vectorA.Combine(vectorB, (a, b) => a * b).Sum(); Console.WriteLine("Dot product: {0}", dotProduct);
15. Query的使用:Deferred Execution、Immediate Execution、Query Reuse。 int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int i = 0; var q = from n in numbers select ++n; foreach (var v in q) { Console.WriteLine("v = {0}, i = {1}", v, ++i); }
16. 集合连接运算: Cross Join、Group Join、Cross Join with Group Join、Left Outer Join。 string[] productsPrefix = new string[]{ "B", "D", "V", "D", "R" };
string[] categories = new string[]{ "Beverages", "Condiments", "Vegetables", "Dairy Products", "Seafood" };
var q = from p in productsPrefix join c in categories on p equals c.Substring(0, 1) select new { p, Category = c};
foreach (var v in q) { Console.WriteLine(v.p + ": " + v.Category); } 有了LINQ(LAMDA表达式)技术的支撑,我们常规的集合计算不需要自己再动手开发代码了,利用此表达式直接计算,真是方便又简洁。