Linq 大合集

        static void Main(string[] args)
        {
            string[] words = { "zero", "one", "two", "three", "four" };
            int[] numbers = { 0, 1, 2, 3, 4 };

            string[] names = { "Robin", "Ruth", "Bob", "Emma" };
            string[] colors = { "Red", "Blue", "Beige", "Green" };

            string[] abbc = { "a", "b", "b", "c" };
            string[] cd = { "c", "d" };

            #region 聚合 立即执行

            //Console.WriteLine(numbers.Sum());//10
            //Console.WriteLine(numbers.Count());//5
            //Console.WriteLine(numbers.Average());//2
            //Console.WriteLine(numbers.LongCount(c => c % 2 == 0));//3
            //Console.WriteLine(words.Min(word => word.Length));//3
            //Console.WriteLine(words.Max(word => word.Length));//5
            //Console.WriteLine(numbers.Aggregate("seed", (current, item) => current + item, result => result.ToUpper()));//SEED01234

            #endregion

            #region 连接 延迟执行 流式数据

            //var result = numbers.Concat(new int[] { 5, 6, 7, 8, 9 });
            //foreach (var i in result)
            //{
            //    Console.WriteLine(i);//0,1,2,3,4,5,6,7,8,9
            //}

            #endregion

            #region 转换

            object[] allStrings = { "these", "are", "all", "strings" };
            object[] notAllStrings = { "number", "at", "the", "end", 5 };

            ////延迟执行 流式数据
            ////allStrings.Cast<string>();//强转,生成 IEnumerable<string> "these", "are", "all", "strings",转换失败则抛出异常
            ////allStrings.OfType<string>();//尝试转换,生成 IEnumerable<string> "these", "are", "all", "strings", 过滤掉转换失败的元素
            ////notAllStrings.Cast<string>();
            ////notAllStrings.OfType<string>();

            ////立即执行
            //numbers.ToArray();
            //numbers.ToList();
            //words.ToDictionary(s => s.Substring(0, 2)).Print();//[ze,zero],[on,one]....
            //var result = words.ToLookup(word => word[0]);

            ///*
            // * z:zero 
            // * o:one
            // * t:two,three
            // * f:four
            // * 
            // */
            //foreach (var item in result)
            //{
            //    Console.WriteLine(item.Key);
            //    foreach (var s in item)
            //    {
            //        Console.WriteLine("--" + s);
            //    }
            //}

            ////words.ToDictionary(word => word[0]);//抛出异常,每个键只能有一个元素,所以在遇到"t"时转换失败

            #endregion

            #region 元素操作符 立即执行

            //Console.WriteLine(words.ElementAt(2));
            //Console.WriteLine(words.ElementAtOrDefault(10));

            //words.First();
            //words.First(f => f.Length == 3);
            //words.FirstOrDefault(f => f.Length > 10);

            //words.Last();

            //words.Single();
            ////...

            #endregion

            #region 相等操作符 立即执行

            //var b1 = words.SequenceEqual(new string[] { "zero", "one", "two", "three", "four" });//true
            //var b2 = words.SequenceEqual(new string[] { "ZERO", "one", "Two", "three", "four" });//false
            //var b3 = words.SequenceEqual(new string[] { "Zero", "one", "Two", "three", "four" }, StringComparer.OrdinalIgnoreCase);//true
            //Console.WriteLine($"{b1},{b2},{b3}");

            #endregion

            #region 生成 延迟执行 流式处理

            //numbers.DefaultIfEmpty();//{ 0, 1, 2, 3, 4 }
            //new int[0].DefaultIfEmpty();//{0}
            //new int[0].DefaultIfEmpty(100);//{100}
            //Enumerable.Range(0, 9);//{0,1,2,3,4,5,6,7,8}
            //Enumerable.Repeat(99, 3);//{99,99,99}
            //Enumerable.Empty<int>();//一个类型为 IEnumerable<int> 的空序列

            #endregion

            #region 分组 延迟执行 缓存数据 当迭代分组的结果序列时,消费的是整个输入序列

            //ToLookup算是其中一个

            //words.GroupBy(word => word.Length);
            //var result = words.GroupBy(word => word.Length, word => word.ToUpper());

            /*
             * 4:ZERO,FOUR
             * 3:ONE,TWO
             * 5:THREE
             */
            //foreach (var item in result)
            //{
            //    Console.WriteLine(item.Key+":");
            //    item.Print();
            //}

            //var result = words.GroupBy(word => word.Length, (key, g) => key + ":" + g.Count());
            //foreach (var item in result)
            //{
            //    item.Print();//4:2,3:2,5:1
            //}


            #endregion

            #region 连接 延迟执行,流式处理左边序列,对于右边序列,在请求第一个结果时变读取其全部内容

            //names.Join(colors, left => left[0], right => right[0], (left, right) => left + ":" + right).Print();
            //Console.WriteLine("**************");
            //names.GroupJoin(colors, left => left[0], right => right[0], (left, right) => left + ":" + string.Join(",", right)).Print();

            #endregion

            #region 分部 延迟执行 流式处理

            //words.Skip(1).Take(2);

            //words.TakeWhile(word => word.Length <= 4);

            //words.SkipWhile(word => word.Length <= 4);

            #endregion

            #region 投影 延迟执行

            //words.Select(word => word.Length);

            //index 表示当前元素在原序列中的索引
            //words.Select((word, index) => index + ":" + word).Print();//0:zero,1:one,2:two...

            //将序列中的每个元素都投影到一个新的序列中
            //words.SelectMany(word => word.ToArray()).Print();//z,e,r,o,o,n,e,t,w,o,t,h,r,e,e,,f,o,u,r

            /*
             * one
             * two
             * two
             * three
             * three
             * three
             * four
             * four
             * four
             * four
             * 
             */
            //words.SelectMany((word, index) => Enumerable.Repeat(word, index)).Print();

            //投影顺序:先是每个序列的第一个元素,接着是每个序列的第二个元素,直到任意一个源序列到达末尾,结果序列都将停止生成
            //names.Zip(colors.Take(3), (left, right) => left + ":" + right).Print();




            #endregion

            #region 数量 立即执行

            words.All(word => word.Length > 2);//true
            words.All(word => word.Length > 6);//false
            words.Any();//true
            words.Any(word => word.Length == 6);//false
            words.Contains("ONE", StringComparer.OrdinalIgnoreCase);//true

            #endregion

            #region 过滤 延迟执行 流式数据

            //OfType 也算过滤

            //words.Where(word => word.Length > 3);
            //words.Where((word, index) => index < word.Length).Print();//four 的索引是 4,长度是 4,所以不会打印出来

            #endregion

            #region 基于集的操作符 延迟执行

            //流式处理
            //abbc.Distinct().Print();//a,b,c

            //四种操作都有该方式的重载
            abbc.Distinct(StringComparer.OrdinalIgnoreCase).Print();//a,b,c

            //abbc.Union(cd).Print();//a,b,c,d

            //左序列流式处理,有序列缓存处理
            //abbc.Intersect(cd).Print();//c
            //abbc.Except(cd).Print();//a,b


            #endregion

            #region 排序 延迟执行 缓存处理

            words.OrderBy(word => word.Length);
            words.OrderByDescending(word => word.Length);
            words.OrderBy(word => word.Length).ThenBy(word => word);
            words.Reverse();

            #endregion

            Console.ReadKey();
        }
原文地址:https://www.cnblogs.com/refuge/p/8707786.html