《LINQ技术详解C#》-5.非延迟操作符(第2部分 LINQ到对象)

1.转换操作符

1.ToArray

从一个类型为T的输入序列创建一个类型为T的数组。

2.ToList

从一个类型为T的序列创建一个类型为T的列表。

3.ToDictionary

从类型为T的序列创建一个类型为<TKey, TSource>的字典,如果该原型包含elementSelector参数,则创建一个类型
<TKey, TElement>的字典。

//
			// 第一个原型:
			 /*Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
             * this IEnumerable<TSource> source, 
             * Func<TSource, TKey> keySelector);*/
            {
                Dictionary<int, Employee> eDictionary =
                    Employee.GetEmployeesArray().ToDictionary(k => k.id);
                Employee e = eDictionary[2];
                Console.WriteLine("Employee whose id == 2 is {0} {1}",e.firstName,e.lastName);
            }

//
			//第二个原型:
             /* Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
             * this IEnumerable<TSource> source, 
             * Func<TSource, TKey> keySelector, 
             * IEqualityComparer<TKey> comparer);    //多一个 IEqualityComparer<TKey> 比较功能
             */


            /* 第三个原型:
             * Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
             * this IEnumerable<TSource> source, 
             * Func<TSource, TKey> keySelector, 
             * Func<TSource, TElement> elementSelector);
             * 与第一原型相比,多一个元素选择器,Dictionary存储的值就可以不同于输入序列元素的类型。
             */
            {
                Dictionary<int, string> eDictionary = Employee.GetEmployeesArray()
               .ToDictionary(k => k.id,
               i => string.Format("{0} {1}", i.firstName, i.lastName)); //elementSelector

                string name = eDictionary[2];
                Console.WriteLine("Employee whose id == 2 is {0}", name);
                //Employee whose id == 2 is Willam Gates
            }

4.ToLookup

单个键可以存储多个值,它是一对多,不像Dictionary<TKey,TElement>一样是一对一的。Lookup<int,int>Dictionary<int,List<int>>是一样的。

从类型T的输入序列中创建一个类型为<TKey, TSource><TKey, TElement>的查找(Lookup),这里TKey是键的类型,TSource是存储的值类型。
如果Lookup类型为<TKey, TElement>,则存储的值类型为TElement,该类型与序列中元素类型T不同。

//第一个原型
            /*ILookup<TKey, TSource> ToLookup<TSource, TKey>(
             * this IEnumerable<TSource> source, 
             * Func<TSource, TKey> keySelector);
             */
            {
                ILookup<int, Actor> lookup = Actor.GetActors().ToLookup(k => k.birthYear);
                //看看是否能找到出生于1964年的人
                IEnumerable<Actor> actors = lookup[1964];
                foreach (var actor in actors)
                    Console.WriteLine("{0} {1}", actor.firstName, actor.lastName);
                //Keanu Reeves, Sandra Bullock
            }
            
 //第三种原型
            /*ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(
             * this IEnumerable<TSource> source, 
             * Func<TSource, TKey> keySelector, 
             * Func<TSource, TElement> elementSelector);*/ 
             //允许开发者指定元素选择器,存储值类型与输入序列元素类型不同
            {
                ILookup<int, string> lookup = Actor.GetActors().ToLookup(k => k.birthYear,
                                  i => string.Format("{0} {1}", i.firstName, i.lastName)); //elementSelector

                //看看是否能找到出生于1964年的人
                IEnumerable<string> actors = lookup[1964];
                foreach (var actor in actors)
                    Console.WriteLine("{0} ", actor);
                //Keanu Reeves, Sandra Bullock
            }

2.相等操作符

1.SequenceEqual

以并行方式枚举每个序列,使用System.Object.Equals方法比较每个序列中的袁旭。如果这些元素全部相等,并且这两个序列具有相同数量元素,
则返回 true,否则返回 false。

//
			/*bool SequenceEqual<TSource>(
             * this IEnumerable<TSource> first, 
             * IEnumerable<TSource> second);*/
            {
                string[] Presidents = { "Adams", "Arthur", "Buchanan" };
                string[] Presidents1 = { "Arthur", "Adams", "Buchanan" };
                bool isEquals = Presidents.SequenceEqual(Presidents1);
                Console.WriteLine(isEquals); //false
            }

3.元素操作符

1.First

返回输入序列第一个元素。

2.FirstOrDefault

返回输入序列第一个元素。如果该序列为空,则返回default(T)。对于引用和可空类型,则默认为null

3.Last

返回一个序列的最后一个元素。

4.LastOrDefault

返回最后一个元素,如果该序列为空,则返回default(T)。对于引用和可空类型,则默认为null

5.Single

只返回单个元素序列中的唯一元素,或者一个匹配谓词的序列中的唯一元素。

6.SingleOrDefault

只返回单个元素序列中的唯一元素,如果该序列为空,则返回 default(T)。对于引用和可空类型,则默认为null
如果找到了多于一个的元素,则产生 InvalidOperationException异常。

7.ElementAt

返回源序列中指定索引的元素。

                Employee emp = Employee.GetEmployeesArray().ElementAt(3);
                Console.WriteLine("{0} {1}",emp.firstName,emp.lastName);

8.ElementAtOrDefault

返回源序列中指定索引的元素。
如果索引小于0或者大于等于序列的元素数量,则返回default(T)。对于引用和可空类型,则默认为null。(与ElementAt的区别)

                Employee emp = Employee.GetEmployeesArray().ElementAtOrDefault(5);
                Console.WriteLine(emp == null ? "NULL" : string.Format("{0} {1}", emp.firstName, emp.lastName));
                //结果:NULL

3.量词操作符

1.Any

任何元素满足某个条件,则Any返回true。

            //第一原型:
            /*Any<TSource>(
             * this IEnumerable<TSource> source);
             * 如果 source 序列包含任何元素,则 Any 返回 true。
             */

            //第二原型:
            /*bool Any<TSource>(
             * this IEnumerable<TSource> source, 
             * Func<TSource, bool> predicate);
             * 如果 predicate 返回 ture,则 Any 返回True。
             */
            {
                string[] Presidents ={
            "Adams", "Arthur", "Buchanan", "Bush", "Carter", "Cleveland",
            "Clinton", "Coolidge", "Eisenhower", "Fillmore", "Ford", "Garfield",
            "Grant", "Harding", "Harrison", "Hayes", "Hoover", "Jackson",
            "Jefferson", "Johnson", "Kennedy", "Lincoln", "Madison", "Mckinley",
            "Monroe", "Nixon", "Pierce", "polk", "Reagan", "Roosevelt", "Taft",
            "taylor", "Trumanyler", "Van Buren", "Washington", "Wilson"
                     };
                bool any = Presidents.Any(); //true
                bool anyPredicate = Presidents.Any(s=>s.StartsWith("Z")); //false
            }

2.All

所有元素都满足某个条件,则返回True。

bool all = Presidents.All(s => s.Length > 5);
                Console.WriteLine(all);//false,不是所有元素长度都大于5

3.Contains

是否包含元素,则返回 true。

5.聚合操作符

1.Count

返回元素中序列的数量。

2.LongCount

long型整数返回输入序列的元素。

3.Sum

返回序列的元素中包含的数字值的总和。

4.Min

返回输入序列中最小值。

//
				int[] myInts = new[] {974, 2, 7, 1374, 27, 54};

                /*Numeric Min(this IEnumerable<Numeric> source);   (Numeric数字类型)*/
                int minInt = myInts.Min();
                Console.WriteLine(minInt);

                /*TSource Min<TSource>(this IEnumerable<TSource> source);
                 * 返回非数字类型*/
                string minName = Presidents.Min();
                Console.WriteLine(minName);

                /*Min<TSource>(
                 * this IEnumerable<TSource> source, 
                 * Func<TSource, Numeric> selector);    (Numeric数字类型)
                 * 用于数字类型,selector委托允许对元素成员变量进行比较 */
                int oldeatActorAge = Actor.GetActors().Min(a => a.birthYear);
                Console.WriteLine(oldeatActorAge);

                /*Min<TSource, TResult>(
                 * this IEnumerable<TSource> source,
                 * Func<TSource, TResult> selector);  
                 * 用于非数字类型 */
                string firstAlphabetically = Actor.GetActors().Min(a => a.lastName);
                Console.WriteLine(firstAlphabetically);
                /*2
                  Adams
                  1960
                  Bullock*/

5.Max

返回输入序列中最大值。

6.Average

返回序列元素的平均值。

7.Aggregate

对序列每个元素执行开发者指定特定函数,将前一个元素的返回值传入该函数,并返回最后一个元素的返回值。

            //第一种原型:
            /* TSource Aggregate<TSource>(
             * this IEnumerable<TSource> source, 
             * Func<TSource, TSource, TSource> func);
             * 对每个元素调用func方法委托,将前一个元素返回值传入委托中作为第一个参数,该元素本身作为第二个参数,
             * 最后将func返回值存储在一个内部加法器中,然后将该值传递到下一个元素,
             * 第一个元素将自身作为输入值传递到 func 方法委托中 */
            {
                int N = 5;
                IEnumerable<int> intSequence = Enumerable.Range(1, N);
                foreach (int sequence in intSequence)
                {
                    Console.WriteLine(sequence);
                }
                //下面计算这个阶乘
                //av==乘积,e==元素
                int agg = intSequence.Aggregate((av, e) => av*e);
                Console.WriteLine("{0}! = {1}",N,agg);
                /* 5! = 120*/
            }

            //第二种原型
            /*TAccumulate Aggregate<TSource, TAccumulate>(
             * this IEnumerable<TSource> source, 
             * TAccumulate seed,           //seed作为第1个参数,而不再是第一个元素本身。
             * Func<TAccumulate, TSource, TAccumulate> func);*/
            {
                IEnumerable<int> intSequence = Enumerable.Range(1,10);
                foreach (int item in intSequence)
                {
                    Console.WriteLine(item);
                }
                Console.WriteLine("----");
                int sum = intSequence.Aggregate(1, (s, i) => s + i);
                Console.WriteLine(sum);
                //56
            }
原文地址:https://www.cnblogs.com/tangge/p/8301401.html