c# intersect怎样使用
导读:在C#中,Intersect方法用于获取两个集合的交集。这个方法通常用在LINQ查询中。以下是如何使用Intersect方法的示例: 首先,我们需要创建两个集合,例如List<int>: List<int> list...
在C#中,Intersect方法用于获取两个集合的交集。这个方法通常用在LINQ查询中。以下是如何使用Intersect方法的示例:
首先,我们需要创建两个集合,例如List<
int>
:
List<
int>
list1 = new List<
int>
{
1, 2, 3, 4, 5 }
;
List<
int>
list2 = new List<
int>
{
4, 5, 6, 7, 8 }
;
接下来,我们可以使用Intersect方法获取这两个集合的交集:
List<
int>
intersection = list1.Intersect(list2).ToList();
在这个例子中,intersection将包含{
4, 5}
,因为这些元素在两个列表中都存在。
如果你想直接在查询中使用Intersect方法,可以这样做:
using System.Linq;
List<
int>
list1 = new List<
int>
{
1, 2, 3, 4, 5 }
;
List<
int>
list2 = new List<
int>
{
4, 5, 6, 7, 8 }
;
var intersection = (from num in list1
join otherNum in list2 on num equals otherNum
select num).ToList();
在这个例子中,我们使用了LINQ查询,通过join关键字将两个列表中的元素进行比较,然后使用select关键字选择交集的元素。最后,我们将结果转换为List<
int>
类型。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c# intersect怎样使用
本文地址: https://pptw.com/jishu/709138.html
