C# Enumerable.Union<TSource> 方法

通过使用默认的相等比较器生成两个序列的并集。
命名空间: System.Linq
程序集: System.Core(在 System.Core.dll 中)

语法

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

类型参数
TSource
输入序列中的元素的类型。

参数
first
类型:System.Collections.Generic.IEnumerable<TSource>,一个 IEnumerable<T>,它的非重复元素构成联合的第一个集。

second
类型:System.Collections.Generic.IEnumerable<TSource>一个 IEnumerable<T>,它的非重复元素构成联合的第二个集。

返回值
类型:System.Collections.Generic.IEnumerable<TSource>一个 IEnumerable<T>,包含两个输入序列中的元素(重复元素除外)。

使用说明
在 Visual Basic 和 C# 中,可以在 IEnumerable<TSource> 类型的任何对象上将此方法作为实例方法来调用。当使用实例方法语法调用此方法时,请省略第一个参数。有关更多信息,请参见扩展方法 (Visual Basic)扩展方法(C# 编程指南)

异常

异常 条件
ArgumentNullException first 或 second 为 null。

备注

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

此方法从结果集中排除重复项。这是与 Concat<TSource> 方法不同的行为,后者返回输入序列中的所有元素,包括重复项。

默认相等比较器 Default 用于比较实现了 IEqualityComparer<T> 泛型接口的类型的值。若要比较自定义类型,需要为该类型实现此接口并提供自己的 GetHashCodeEquals 方法。

当枚举此方法返回的对象时,Union 会按顺序枚举 first 和 second,并生成尚未生成的每个元素。

示例

下面的代码示例演示如何使用 Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) 获取两个整数序列的集合。

            int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 };
            int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 };

            IEnumerable<int> union = ints1.Union(ints2);

            foreach (int num in union)
            {
                Console.Write("{0} ", num);
            }
            /*
             This code produces the following output:

             5 3 9 7 8 6 4 1 0
            */

如果希望比较自定义数据类型的对象的序列,则必须在类中实现 IEqualityComparer<T> 泛型接口。下面的代码示例演示如何在自定义数据类型中实现此接口并提供 GetHashCodeEquals 方法。

public class ProductA
{ 
    public string Name { get; set; }
    public int Code { get; set; }
}

public class ProductComparer : IEqualityComparer<ProductA>
{
    public bool Equals(ProductA x, ProductA y)
    {
        //Check whether the objects are the same object. 
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether the products' properties are equal. 
        return x != null && y != null && x.Code.Equals(y.Code) && x.Name.Equals(y.Name);
    }

    public int GetHashCode(ProductA obj)
    {
        //Get hash code for the Name field if it is not null. 
        int hashProductName = obj.Name == null ? 0 : obj.Name.GetHashCode();

        //Get hash code for the Code field. 
        int hashProductCode = obj.Code.GetHashCode();

        //Calculate the hash code for the product. 
        return hashProductName ^ hashProductCode;
    }
}

实现此接口后,您可以使用的序列 ProductA 中的对象 Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) 方法,如下面的示例中所示。

ProductA[] store1 = { new ProductA { Name = "apple", Code = 9 }, 
                       new ProductA { Name = "orange", Code = 4 } };

ProductA[] store2 = { new ProductA { Name = "apple", Code = 9 }, 
                       new ProductA { Name = "lemon", Code = 12 } };
//Get the products from the both arrays
//excluding duplicates.

IEnumerable<ProductA> union = store1.Union(store2, new ProductComparer());//自定义类型时使用自己的比较方法

foreach (var product in union)
    Console.WriteLine(product.Name + " " + product.Code);

/*
    This code produces the following output:

    apple 9
    orange 4
    lemon 12
*/
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,765评论 18 399
  • 1、面向对象的特征有哪些方面 1.抽象:抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标...
    michaelgong阅读 851评论 0 1
  • 对象的创建与销毁 Item 1: 使用static工厂方法,而不是构造函数创建对象:仅仅是创建对象的方法,并非Fa...
    孙小磊阅读 2,031评论 0 3
  • 传销模式尤以“拉人头”的异地邀约传销危害最为严重,通过人身、精神、资金等达到控制的目的。当新人刚被骗到异地后,不让...
    w不做差不多小姐阅读 292评论 0 0
  • 雨终于是下下来了,大雨,缓解了一下炎热。下班回家,正坐在小木马上摇啊摇,一边摇,嘴巴里还念念有词的,原来是在念成语...
    Jerryboy阅读 220评论 0 1