前面说到LINQ to Object——延时执行的Enumerable类的方法,接下来说说LINQ to Object——立即执行的Enumerable类方法。
1.ToArray 序列转换成数组
List<string> names_list = new List<string> { "张三", "范冰冰", "李冰冰", "迈克尔·杰克逊", "李四", "王五", "赵六", "田七" }; string[] takenames_arry = names_list.ToArray(); string[] takenames_arry2 = (from name in names_list select name).Take(4).ToArray(); foreach (var name in takenames_arry2) { Console.WriteLine(name); } Console.WriteLine("----------------------------"); Console.ReadKey();
运行结果:
2.ToList 序列转换成List<T>
string[] names_array = { "张三", "范冰冰", "李冰冰", "迈克尔·杰克逊", "李四", "王五", "赵六", "田七" }; List<string> takenames_list = names_array.ToList(); List<string> takenames_list2 = (from name in names_array select name).Skip(4).ToList(); foreach (var name in takenames_list2) { Console.WriteLine(name); } Console.WriteLine("----------------------------"); Console.ReadKey();
运行结果:
3.ToDictionary 把序列转换为泛型Dictionary<TKey,TValue>
List<Person> personList = new List<Person>() { new Person(){ Name = "张三", Age = 12, Phone = "555555"}, new Person(){ Name = "李四", Age = 23, Phone = "666666"}, new Person(){ Name = "王五", Age = 14, Phone = "777777"}, new Person(){ Name = "赵六", Age = 25, Phone = "888888"}, new Person(){ Name = "田七", Age = 16, Phone = "999999"}, };
Dictionary<string, Person> dictionary_person = personList.ToDictionary(guest => guest.Name); foreach (var person in dictionary_person) { Console.WriteLine("键:{0}——值:{1} {2} {3}", person.Key, person.Value.Name, person.Value.Age, person.Value.Phone); } Console.WriteLine("--------------------------------"); Console.ReadKey(); Dictionary<string, string> dictionary_person2 = personList.ToDictionary(person => person.Name, person => person.Phone); foreach (var person in dictionary_person2) { Console.WriteLine("键:{0}——值:{1}", person.Key, person.Value); } Console.WriteLine("--------------------------------"); Console.ReadKey();
运行结果:
注意:Dictionary的Key和Value是一一对应关系。
4.ToLookup 用于将序列转换为泛型Lookup<TKey,TValue>
和ToDictionary类似,不细写代码了。
注意:Lookup的Key和Value是一对多关系,Lookup没有公共构造函数,只能用ToLookup构建,创建后也不能删除Lookup中的元素。
5.SequenceEqual 比较两个序列是否相等
bool sequence_equal = names_array.SequenceEqual(names_list); bool sequence_equal2 = names_array.Skip(1).Take(2).SequenceEqual(names_list.Take(3).SkipWhile(n => n.Length == 2)); Console.WriteLine("{0},{1}", sequence_equal, sequence_equal2); Console.WriteLine("----------------------------"); Console.ReadKey();
运行结果:
6.First 返回序列第一个满足条件元素
var first_name = names_array.First(); var first_name2 = names_array.First(n => n.Length == 3); Console.WriteLine("{0},{1}", first_name, first_name2); Console.WriteLine("----------------------------"); Console.ReadKey();
运行结果:
7.FirstOrDefault 返回序列第一个满足条件元素,如果没有找到则返回默认值
var first_or_default_name = names_array.FirstOrDefault(); var first_or_default_name2 = names_array.FirstOrDefault(n => n == "123"); Console.WriteLine("{0},{1}", first_or_default_name, first_or_default_name2); Console.WriteLine("----------------------------"); Console.ReadKey();
运行结果:
8.Last 返回序列最后一个满足条件元素
var last_name = names_array.Last(); var last_name2 = names_array.LastOrDefault(n => n.Length == 3); Console.WriteLine("{0},{1}", last_name, last_name2); Console.WriteLine("----------------------------"); Console.ReadKey();
运行结果:
9.LastOrDefault 返回序列最后一个满足条件元素,如果没有找到则返回默认值
var last_or_default_name = names_array.LastOrDefault(); var last_or_default_name2 = names_array.LastOrDefault(n => n == "123"); Console.WriteLine("{0},{1}", last_or_default_name, last_or_default_name2); Console.WriteLine("----------------------------"); Console.ReadKey();
运行结果:
10.Single 返回序列中唯一的元素,注意:如果序列中包含多个元素,会引发运行错误
try { var single_name = names_array.Single(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("----------------------------"); var single_name2 = names_array.Single(n => n == "张三"); Console.WriteLine("{0}", single_name2); Console.WriteLine("----------------------------"); Console.ReadKey();
运行结果:
11.SingleOrDefault 找出序列中满足一定条件的元素,注意:如果序列为空则返回默认值, 如果序列中包含多个多个元素会引发运行错误
try { var single_or_default_name = Enumerable.Empty<int>().SingleOrDefault(); Console.WriteLine("{0}", single_or_default_name);//不报错,如果序列为空就返回默认值 } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("----------------------------"); try { var single_or_default_name2 = names_array.SingleOrDefault(); Console.WriteLine("{0}", single_or_default_name2);//报错,序列包含多行错误 } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("----------------------------"); var single_or_default_name3 = Enumerable.Empty<string>().DefaultIfEmpty("默认值").SingleOrDefault(); Console.WriteLine("{0}", single_or_default_name3); Console.WriteLine("----------------------------"); var single_or_default_name4 = names_array.SingleOrDefault(n => n == "123"); Console.WriteLine("{0}", single_or_default_name4); Console.WriteLine("----------------------------"); Console.ReadKey();
运行结果:
12.ElementAt 获得指定索引处的元素
var element_at_name = names_array.ElementAt(3); Console.WriteLine("{0}", element_at_name); Console.WriteLine("----------------------------"); Console.ReadKey();
运行结果:
13.ElementAtOrDefault 获得指定索引处的元素,如果超出索引,则返回元素类型的默认值
var element_at_or_default_name = names_array.ElementAtOrDefault(5); var element_at_or_default_name2 = names_array.ElementAtOrDefault(10); Console.WriteLine("{0},{1}", element_at_or_default_name, element_at_or_default_name2); Console.WriteLine("----------------------------"); Console.ReadKey();
运行结果:
14.All 序列中的所有元素是否都满足条件
bool all_names = names_array.All(s => s.GetTypeCode() == TypeCode.String); bool all_names2 = names_array.All(s => s.Length < 10); Console.WriteLine("{0},{1}", all_names, all_names2); Console.WriteLine("----------------------"); Console.ReadKey();
运行结果:
15.Any 序列中的元素是否存在或满足条件
bool any_names = names_array.Any(); bool any_names2 = names_array.Any(s => s.Length > 7); Console.WriteLine("{0},{1}", any_names, any_names2); Console.WriteLine("----------------------"); Console.ReadKey();
运行结果:
16.Contains 确定元素是否在序列中
bool contains_name = names_array.Contains("田"); Console.WriteLine("{0}", contains_name); Console.WriteLine("----------------------"); Console.ReadKey();
运行结果:
17.Count 序列包含元素的数量
int count_names = names_array.Count(); int count_names2 = names_array.Count(n => n.Length == 7); Console.WriteLine("{0},{1}", count_names, count_names2); Console.WriteLine("----------------------"); Console.ReadKey();
运行结果:
18.LongCount 获取一个Int64类型的元素数量
long longcount_names = names_array.LongCount(); long longcount_names2 = names_array.LongCount(n => n.Length == 3); Console.WriteLine("{0},{1}", longcount_names, longcount_names2); Console.WriteLine("----------------------"); Console.ReadKey();
运行结果:
19.Aggregate 将序列元素进行累加
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 21, 22, 232, 8, 64, 9, 46, 7 }; int aggregate_numbers = numbers.Aggregate((n1, n2) => n1 + n2); int aggregate_numbers2 = numbers.Aggregate(99, (n1, n2) => n1 + n2); Console.WriteLine("{0},{1}", aggregate_numbers, aggregate_numbers2); Console.WriteLine("----------------------"); Console.ReadKey(); string aggregate_names = names_array.Aggregate((name1, name2) => string.Format("{0}、{1}", name1, name2));//相当于name1 += name2 string aggregate_names2 = names_array.Aggregate("累加结果:", (name1, name2) => string.Format("{0}、{1}", name1, name2)); Console.WriteLine("{0}", aggregate_names); Console.WriteLine("{0}", aggregate_names2); Console.WriteLine("----------------------"); Console.ReadKey();
运行结果:
20.Sum 序列之和
21.Average 序列平均值
22.Min 序列的最小值
23.Max 序列的最大值
//20、Sum序列之和 int sum_numbers = numbers.Sum(); Console.WriteLine(sum_numbers); Console.WriteLine("----------------------"); //21、Average序列平均值 double avg_numbers = numbers.Average(); Console.WriteLine(avg_numbers); Console.WriteLine("----------------------"); //22、Min序列的最小值 int min_numbers = numbers.Min(); Console.WriteLine(min_numbers); Console.WriteLine("----------------------"); //23、Max序列的最大值 int max_numbers = numbers.Max(); Console.WriteLine(max_numbers); Console.WriteLine("----------------------"); Console.ReadKey();
运行结果:
常用立即执行的Enumerable类方法学习和整理完毕!