C#对List取交集、差集及并集

1. 交集

(1)取交集 
List 1 : { 1 , 2 , 3 , 5 , 9 }
List 2 : { 4 , 3 , 9 }

var intersectedList = list1.Intersect(list2).ToList();

结果 : { 3 , 9 }

(2)判断是否有交集

bool isIntersected = list1.Intersect(list2).Count() > 0

2. 差集

(1)取差集 
List 1 : { 1 , 2 , 3 , 5 , 9 }
List 2 : { 4 , 3 , 9 }

var expectedList = list1.Except(list2).ToList();

结果 : { 1 , 2 , 5 }

(2)判断是否有差集

bool isExpected = list1.Expect(list2).Count() > 0

3. 并集

(1)取并集
List 1 : { 1 , 2 , 3 , 5 , 9 }
List 2 : { 4 , 3 , 9 }

var unionList = list1.Union(list2).ToList();

结果 : { 1 , 2 , 3 , 5 ,9 , 4 }

如果把

unionList = list1.Union(list2).ToList();

换成

unionList = list1.Concat(list2).ToList();

list1.AddRange(list2);

unionList .AddRange(list1);

则将会保留重复项

结果 : { 1 , 2 , 3 , 5 , 9 , 4 , 3 , 9 }

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java 8 中可以使用 Stream API 来实现集合之间的交集并集差集、去重并集。 假设有两个 List 集合:list1 和 list2,分别包含一些元素,代码如下: ```java List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5); List<Integer> list2 = Arrays.asList(4, 5, 6, 7, 8); ``` 下面分别介绍如何实现集合之间的操作。 1. 交集 交集即获两个集合中共同拥有的元素。可以使用 Stream API 的 `filter()` 方法和 `contains()` 方法实现。代码如下: ```java List<Integer> intersection = list1.stream() .filter(list2::contains) .collect(Collectors.toList()); System.out.println("交集:" + intersection); // 输出 [4, 5] ``` 2. 并集 并集即获两个集合中所有的元素,但是去重。可以使用 Stream API 的 `distinct()` 方法和 `concat()` 方法实现。代码如下: ```java List<Integer> union = Stream.concat(list1.stream(), list2.stream()) .distinct() .collect(Collectors.toList()); System.out.println("并集:" + union); // 输出 [1, 2, 3, 4, 5, 6, 7, 8] ``` 3. 差集 差集即获两个集合中不同的元素。可以使用 Stream API 的 `filter()` 方法和 `!contains()` 方法实现。代码如下: ```java List<Integer> diff1 = list1.stream() .filter(e -> !list2.contains(e)) .collect(Collectors.toList()); System.out.println("差集1:" + diff1); // 输出 [1, 2, 3] List<Integer> diff2 = list2.stream() .filter(e -> !list1.contains(e)) .collect(Collectors.toList()); System.out.println("差集2:" + diff2); // 输出 [6, 7, 8] ``` 4. 去重并集 去重并集即获两个集合中所有的元素,并且去重。可以使用 Stream API 的 `distinct()` 方法和 `flatMap()` 方法实现。代码如下: ```java List<Integer> distinctUnion = Stream.of(list1, list2) .flatMap(List::stream) .distinct() .collect(Collectors.toList()); System.out.println("去重并集:" + distinctUnion); // 输出 [1, 2, 3, 4, 5, 6, 7, 8] ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值