一、Grouping(分组)
例1:对于0-9数按被3整除的结果分组
代码:
1 static void Linq1() 2 { 3 int[] numbers = { 5, 3, 2, 4, 0, 7, 8, 6, 9, 1 }; 4 var numModBy3 = from n in numbers 5 group n by n % 3 6 into g 7 select new { Remainder = g.Key, Numbers = g }; 8 9 foreach (var g in numModBy3) 10 { 11 Console.Write("被3整除余 {0} : ", g.Remainder); 12 foreach (var num in g.Numbers) 13 { 14 Console.Write("{0} ", num); 15 } 16 Console.WriteLine(); 17 } 18 }
例2:对单词按首字母分组
代码:
1 static void Linq2() 2 { 3 string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" }; 4 var groupedData = from w in words 5 group w by w[0] 6 into g 7 orderby g.Key // 加排序 8 select new { FirstChar = g.Key, Words = g }; 9 foreach (var g in groupedData) 10 { 11 Console.Write("以 {0} 字母开头的有 : ", g.FirstChar); 12 foreach (var word in g.Words) 13 { 14 Console.Write("{0} ", word); 15 } 16 Console.WriteLine(); 17 } 18 }
二、Set(集合)
Distinct去重
source.Distinct();
其他 Union、Intersect、Except 参见 LINQ 101 Sample
三、Conversion(转换)
ToList
ToDictionary
四、Element(元素操作)
First
FirstOrDefault
时间: 2024-10-14 03:57:05