C# Linq 详解四

目录

概述

二十、SelectMany

二十一、Aggregate

二十二、DistinctBy

二十三、Reverse

二十四、SequenceEqual

二十五、Zip

二十六、SkipWhile 

二十七、TakeWhile


C# Linq 详解一
1.Where
2.Select
3.GroupBy
4.First / FirstOrDefault
5.Last / LastOrDefault

C# Linq 详解二
1.OrderBy 
2.OrderByDescending
3.Skip
4.Take
5.Any
6.All

C# Linq 详解三
1.Sum / Min / Max / Average
2.Distinct
3.Concat
4.Join
5.ToList 
6.ToArray
7.ToDictionary

C# Linq 详解四
1.SelectMany
2.Aggregate
3.DistinctBy
4.Reverse
5.SequenceEqual
6.Zip
7.SkipWhile 
8.TakeWhile
 

C# Linq 详解一_熊思宇的博客-CSDN博客

C# Linq 详解二_熊思宇的博客-CSDN博客

C# Linq 详解三_熊思宇的博客-CSDN博客

概述

语言集成查询 (LINQ) 是一系列直接将查询功能集成到 C# 语言的技术统称。 数据查询历来都表示为简单的字符串,没有编译时类型检查或 IntelliSense 支持。 此外,需要针对每种类型的数据源了解不同的查询语言:SQL 数据库、XML 文档、各种 Web 服务等。 借助 LINQ,查询成为了最高级的语言构造,就像类、方法和事件一样。

对于编写查询的开发者来说,LINQ 最明显的“语言集成”部分就是查询表达式。 查询表达式采用声明性查询语法编写而成。 使用查询语法,可以用最少的代码对数据源执行筛选、排序和分组操作。 可使用相同的基本查询表达式模式来查询和转换 SQL 数据库、ADO .NET 数据集、XML 文档和流以及 .NET 集合中的数据。

二十、SelectMany

SelectMany 用于将嵌套的集合展开成一个扁平的序列

这个解释有点难以理解,用案例来解释最好不过了

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<Student> students = new List<Student>
            {
                new Student { Id = 1, Name = "John", Courses = new List<string> { "Math", "English" } },
                new Student { Id = 2, Name = "Jane", Courses = new List<string> { "Science", "History" } },
                new Student { Id = 3, Name = "Mike", Courses = new List<string> { "Art", "Music" } }
            };
            var allCourses = students.SelectMany(s => s.Courses);
            foreach (var course in allCourses)
            {
                Console.WriteLine(course);
            }

            Console.ReadKey();
        }
    }

    class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<string> Courses { get; set; }
    }
}

运行:

二十一、Aggregate

使用指定的累加器函数对序列中的元素进行累积计算。

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 1, 2, 3, 4, 5 };
            int sum = numbers.Aggregate((acc, num) => acc + num);
            Console.WriteLine("结果:{0}", sum); 

            Console.ReadKey();
        }
    }
}

运行:

在 Aggregate((acc, num) => acc + num) 这句可以看到,有两个参数,是这样,它是先取两个参数,1 + 2 = 3,第二次再拿 3 + 3 = 6,如此类推,最终的结果等于 15

二十二、DistinctBy

DistinctBy 是一个自定义的扩展方法,它用于按照指定的属性或条件对序列中的元素进行去重操作。

去重操作,看的有点蒙,其实就是去除重复的元素,这个方法用法也是花样很多,可以搜到很多种玩法,只是我基本不用的,哈哈。

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<Person> people = new List<Person>
            {
                new Person { Id = 1, Name = "John" },
                new Person { Id = 2, Name = "Jane" },
                new Person { Id = 3, Name = "John" }
            };

            var distinctPeople = people.DistinctBy(p => p.Name);
            foreach (var person in distinctPeople)
            {
                Console.WriteLine(person.Name);
            }

            Console.ReadKey();
        }
    }

    class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public static class EnumerableExtensions
    {
        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
            this IEnumerable<TSource> source, 
            Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }
    }
}

运行:

二十三、Reverse

将序列中的元素按照相反的顺序返回。

这个非常简单,直接上案例

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 1, 2, 3, 4, 5 };
            var reversedNumbers = numbers.Reverse();
            foreach (var number in reversedNumbers)
            {
                Console.WriteLine(number);
            }

            Console.ReadKey();
        }
    }
}

运行:

二十四、SequenceEqual

SequenceEqual 用于比较两个序列是否相等。

这个方法,两个数组必须一模一样才会返回 true,而且类型也必须一样

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[] numbers1 = { 1, 2, 3, 4, 5 };
            int[] numbers2 = { 1, 2, 3, 4, 5 };
            bool areEqual = numbers1.SequenceEqual(numbers2);
            Console.WriteLine(areEqual); 

            Console.ReadKey();
        }
    }
}

运行:

二十五、Zip

zip 用于将两个序列按照索引位置进行配对。

下面这个案例中,把两个数组一对一进行相加,并根据原来的下标,重新生成了一个新的数组

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[] numbers1 = { 1, 2, 3 };
            int[] numbers2 = { 10, 20, 30 };
            var zippedNumbers = numbers1.Zip(numbers2, (n1, n2) => n1 + n2);
            foreach (var number in zippedNumbers)
            {
                Console.WriteLine(number);
            }

            Console.ReadKey();
        }
    }
}

运行:

二十六、SkipWhile 

SkipWhile 用于跳过序列中满足指定条件的元素,直到遇到第一个不满足条件的元素。

注意这里,是不满足条件,下面的案例中,n 指的就是数组中的每个元素,在遍历到 n 不满足  n < 3 这个条件时,才开始返回集合。

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 1, 2, 3, 4, 5 };
            var skippedNumbers = numbers.SkipWhile(n => n < 3);
            foreach (var number in skippedNumbers)
            {
                Console.WriteLine(number);
            }

            Console.ReadKey();
        }
    }
}

运行:

二十七、TakeWhile

TakeWhile 用于获取序列中满足指定条件的连续元素,直到遇到第一个不满足条件的元素。

TakeWhile 和 SkipWhile 刚好相反,用起来也是比较简单的。

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 1, 2, 3, 4, 5 };
            var takenNumbers = numbers.TakeWhile(n => n < 4);
            foreach (var number in takenNumbers)
            {
                Console.WriteLine(number);
            }

            Console.ReadKey();
        }
    }
}

运行:

end

猜你喜欢

转载自blog.csdn.net/qq_38693757/article/details/131441602