参考官方文档
一、交集Intersect
Enumerable.Intersect 方法
定义
命名空间:
程序集:
System.Linq.dll
生成两个序列的交集。
参数
first
IEnumerable<TSource>
一个 IEnumerable<T>,将返回其也出现在 second
中的非重复元素。
second
IEnumerable<TSource>
一个 IEnumerable<T> 序列,其中的同时出现在第一个序列中的非重复元素将被返回。
comparer
IEqualityComparer<TSource>
用于比较值的 IEqualityComparer<T>。
返回
System.Linq<TSource>
包含组成两个序列交集的元素的序列。
二、并集Concat
Enumerable.Concat<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) 方法
定义
命名空间:
程序集:
System.Linq.dll
连接两个序列。
三、去重Distinct
Enumerable.Distinct 方法
定义
命名空间:
程序集:
System.Linq.dll
返回序列中的非重复元素。
注解
结果序列是无序的。
四、差集Except
Enumerable.Except 方法
定义
命名空间:
程序集:
System.Linq.dll
生成两个序列的差集。
注解
这两个集的差集定义为第一个集的成员,但第二个集未出现。
差集:先将两个集合重复的数据删除,再返回只在第一个集合中出现,在第二个集合中不出现的所有行,差集会自动去除重复元素,相当于返回 第一个集合的子集【元素不在第二个集合中】
此方法返回中 first
不显示的那些元素 second
。 它不会返回中 second
不显示的元素 first
。 仅返回唯一元素。
测试程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SetOperationDemo
{
class Program
{
static void Main(string[] args)
{
List<int> A = new List<int> { 2, 3, 4, 5, 6, 7, 7, 8 };
List<int> B = new List<int> { 1, 3, 5, 7, 9, 9, 11 };
Console.WriteLine($"【交集Intersect】:{string.Join(",", A.Intersect(B))}");
Console.WriteLine($"【并集有重复Concat】:{string.Join(",", A.Concat(B))}");
Console.WriteLine($"【并集无重复Distinct】:{string.Join(",", A.Concat(B).Distinct())}");
//差集:先将两个集合相等的数据删除,再返回只在第一个集合中出现,在第二个集合中不出现的所有行
//差集会自动去除重复
Console.WriteLine($"【差集Except】A-B:{string.Join(",", A.Except(B))}");
Console.WriteLine($"【差集Except】B-A:{string.Join(",", B.Except(A))}");
IEnumerable<int> test = new List<int> { 2, 2, 3, 3, 18 }.Except(new List<int> { 2, 2, 2, 4 });
Console.WriteLine($"【差集Except将自动去除重复元素】.差集:{string.Join(",", test)}");
//inner join 相同的元素后,进行相加
IEnumerable<int> joinResult = A.Join(B, a => a, b => b, (a, b) => a + b);
Console.WriteLine($"【关联Join】:{string.Join(",", joinResult)}");
Console.ReadLine();
}
}
}
运行结果