当前位置: 移动技术网 > IT编程>开发语言>.net > 【转载】 C#使用Union方法求两个List集合的并集数据

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

2019年05月13日  | 移动技术网IT编程  | 我要评论

乔四爷玩过的女人,qq号价值评估,撕夜吉他谱

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

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

list<int> list1 = new list<int> { 1, 2, 3, 4 };
list<int> list2 = new list<int> { 3, 4, 5, 6 };

list<int>  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交集运算可参考此文:。

备注:原文转载自博主个人站点it技术小趣屋,原文链接: 。

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网