代码改变世界

交集:通过使用默认的相等比较器对值进行比较生成两个序列的交集

2008-12-23 11:15  Valens  阅读(290)  评论(0编辑  收藏  举报

支持.net 3.5

语法:

public static IEnumerable<TSource> Intersect<TSource>(
    
this IEnumerable<TSource> first,
    IEnumerable
<TSource> second
)

 

类型参数

TSource

输入序列中的元素的类型。

参数

first
类型:System.Collections.Generic..::.IEnumerable<(Of <(TSource>)>)

一个 IEnumerable<(Of <(T>)>),将返回其也出现在 second 中的非重复元素。

second
类型:System.Collections.Generic..::.IEnumerable<(Of <(TSource>)>)

一个 IEnumerable<(Of <(T>)>),将返回其也出现在第一个序列中的非重复元素。

返回值

类型:System.Collections.Generic..::.IEnumerable<(Of <(TSource>)>)

包含组成两个序列交集的元素的序列。  

此方法通过使用延迟执行实现。即时返回值为一个对象,该对象存储执行操作所需的所有信息。只有通过直接调用对象的 GetEnumerator 方法或使用 Visual C# 中的 foreach(或 Visual Basic 中的 For Each)来枚举该对象时,才执行此方法表示的查询。

集 A 和集 B 的交集定义为包含同时出现在 A 和 B 中的所有元素的集,但不包含任何其他元素。

当枚举此方法返回的对象时,Intersect 将枚举 first,以收集该序列中的所有非重复元素。然后,枚举 second,从而标记那些同时出现在两个序列中的元素。最后,按收集顺序生成标记的元素。

使用默认的相等比较器 Default 对值进行比较。

集 A 和集 B 的交集定义为包含同时出现在 A 和 B 中的所有元素的集,但不包含任何其他元素。

下面的代码示例演示如何使用 Intersect<(Of <(TSource>)>)(IEnumerable<(Of <(TSource>)>), IEnumerable<(Of <(TSource>)>)) 返回同时出现在两个序列中的元素。

int[] id1 = { 442692307138 };
int[] id2 = { 3959834726430 };

IEnumerable
<int> both = id1.Intersect(id2);

foreach (int id in both)
    Console.WriteLine(id);

/*
 This code produces the following output:

 26
 30
*/

 

 http://msdn.microsoft.com/zh-cn/library/bb460136.aspx