先看2个例子
例子1.选择整数数组中的偶数,并且顺序排列。
int[] numbers = { 5, 10, 8, 3, 6, 12 }; IEnumerable<int> numQuery = numbers.Where(num => num % 2 == 0).OrderBy(n => n).Select(o=>o); foreach (int i in numQuery) Console.Write(i + " ");
输出 6 8 10 12
例子2.从一组对象中,选择Name 以J为起始,Rank 降序排列,结果为对象中Name的集合。
public class person { public string Name { get; set; } public int Rank { get; set; } } person[] ps = new person[]{ new person(){Name="Jerry",Rank=3}, new person(){Name="Tom",Rank=4}, new person(){Name="Larry",Rank=2}, new person(){Name="John",Rank=23} }; var result = ps.Where(e => e.Name.StartsWith("J")).OrderByDescending(n => n.Rank).Select(o => o.Name); foreach(var v in result) { Console.WriteLine(v); }
输出
John
Jerry
说明:
Where OrderBy Select都是IEnumerable<TSource>的扩展方法
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate); public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector); 其中public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2); public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector); 其中 public delegate TResult Func<T, TResult>(T arg);
例子3. 词典中根据Value查找Key的集合。
Dictionary<int, string> c = new Dictionary<int, string>(); c.Add(1, "11"); c.Add(2, "8"); c.Add(3,"12"); c.Add(4,"12"); c.Add(5,"13"); var result = c.Where(e => e.Value.Equals("12")).Select(e => e.Key);
因为Dictionary本质是IEnumerable<KeyValuePair<TKey, TValue>>
例子4.对字符串数组进行分组。
List<string> list = new List<string>() { "1_32", "2_10", "1_8", "1_25", "2_3", "3_5", "5_15", "3_16" }; var groupList2 = list.GroupBy(s => s.Split('_')[0]).Select(g => g); foreach(var group in groupList2) { foreach(var item in group) { Console.WriteLine("With Key " + group.Key + " " + item.ToString()); } }
用_前的数字做key分组,打印每组的值
输出:
With Key 1 1_32
With Key 1 1_8
With Key 1 1_25
With Key 2 2_10
With Key 2 2_3
With Key 3 3_5
With Key 3 3_16
With Key 5 5_15
或者输出每组 的个数
var groupList3=list.GroupBy(s=>s.Split('_')[0]).Select(g=>new {mykey=g.Key,count=g.Count()}); foreach(var item in groupList3) { Console.WriteLine("With Key " + item.mykey + " has " + item.count); }
输出:
With Key 1 has 3
With Key 2 has 2
With Key 3 has 2
With Key 5 has 1
参阅:
https://www.cnblogs.com/heyuquan/p/Linq-to-Objects.html
https://www.cnblogs.com/willick/p/13586024.html