【转载】 C#使用Union方法求两个List集合的并集数据

在C#语言的编程开发中,有时候需要对List集合数据进行运算,如对两个List集合进行交集运算或者并集运算,其中针对2个List集合的并集运算,可以使用Union方法来快速实现,Union方法的调用格式为List1.Union(List2),List1和List2为同类型的List集合数据。

(1)针对值类型的List集合,两个集合的合并即以值是否相同为准进行合并。例如以下两个List集合,list1的值为1、2、3、4。list2的值为3、4、5、6。则求它们并集可使用list1.Union(list2)快速实现。

List list1 = new List { 1, 2, 3, 4 };
List list2 = new List { 3, 4, 5, 6 };

List unionjiList = list1.Union(list2).ToList();
上述结果语句求得unionjiList 结果为:unionjiList 中含有5个元素,为1,2,3,4,5。

(2)针对引用类型的对象List集合,如自定义类对象的List集合,判断是否为同一个元素的规则是判断对象的引用指针是否一致,如果两个集合中的两个对象的所有属性值都一样,但对象的引用地址不同,也是2个不同的值,在并集中会同时出现这2个元素。具体举例如下:

       List<TestModel> list1 = new List<TestModel>();
       list1.Add(new TestModel() { Index = 1, Name = "TestModel1" });
        list1.Add(new TestModel() { Index = 2, Name = "TestModel2" });
        list1.Add(new TestModel() { Index = 3, Name = "TestModel3" });
        list1.Add(new TestModel() { Index = 4, Name = "TestModel4" });

        List<TestModel> list2 = new List<TestModel>();
        list2.Add(new TestModel() { Index = 3, Name = "TestModel3" });
        list2.Add(new TestModel() { Index = 4, Name = "TestModel4" });
        list2.Add(new TestModel() { Index = 5, Name = "TestModel5" });
        list2.Add(new TestModel() { Index = 6, Name = "TestModel6" });

        List<TestModel> unionjiList = list1.Union(list2).ToList();

上述语句的运行结果为:unionjiList集合一共有8个对象,8个对象的属性值即为上述语句Add里面的一致。并没有把list1和list2中的Index=3或4的两个对象视为同一个元素。但如果是下列语句写法,则unionjiList集合中只有6个元素,unionjiList集合中Index为3或4的对象就各只有一个了。

        TestModel model1 = new TestModel() { Index = 1, Name = "TestModel1" };
        TestModel model2 = new TestModel() { Index = 2, Name = "TestModel2" };
        TestModel model3 = new TestModel() { Index = 3, Name = "TestModel3" };
        TestModel model4 = new TestModel() { Index = 4, Name = "TestModel4" };
        TestModel model5 = new TestModel() { Index = 5, Name = "TestModel5" };
        TestModel model6 = new TestModel() { Index = 6, Name = "TestModel6" };

        list1.Add(model1);
        list1.Add(model2);
        list1.Add(model3);
        list1.Add(model4);

        list2.Add(model3);
        list2.Add(model4);
        list2.Add(model5);
        list1.Add(model6);

        List<TestModel> unionjiList = list1.Union(list2).ToList();

关于List集合的并集运算的阐述就到这,相应的List交集运算可参考此文:C#编程中两个List集合使用Intersect方法求交集

备注:原文转载自博主个人站点IT技术小趣屋,原文链接: C#使用Union方法求两个List集合的并集数据_IT技术小趣屋

猜你喜欢

转载自blog.csdn.net/weixin_39650424/article/details/93380677
今日推荐