Pet*_*ger 264 .net c# collections intersect
Intersect可用于查找两个集合之间的匹配,如下所示:
// Assign two arrays.
int[] array1 = { 1, 2, 3 };
int[] array2 = { 2, 3, 4 };
// Call Intersect extension method.
var intersect = array1.Intersect(array2);
// Write intersection to screen.
foreach (int value in intersect)
{
Console.WriteLine(value); // Output: 2, 3
}
Run Code Online (Sandbox Code Playgroud)
然而,我想要实现的是相反的,我想列出比较两个集合时缺少的项目:
// Assign two arrays.
int[] array1 = { 1, 2, 3 };
int[] array2 = { 2, 3, 4 };
// Call "NonIntersect" extension method.
var intersect = array1.NonIntersect(array2); // I've made up the NonIntersect method
// Write intersection to screen.
foreach (int value in intersect)
{
Console.WriteLine(value); // Output: 4
}
Run Code Online (Sandbox Code Playgroud)
Øyv*_*hen 364
如上所述,如果你想得到4作为结果,你可以这样做:
var nonintersect = array2.Except(array1);
Run Code Online (Sandbox Code Playgroud)
如果你想要真正的非交集(同时也是1和4),那么这应该可以解决问题:
var nonintersect = array1.Except(array2).Union( array2.Except(array1));
Run Code Online (Sandbox Code Playgroud)
这不是最高性能的解决方案,但对于小型列表,它应该可以正常工作.
seh*_*ehe 84
您可以使用
a.Except(b).Union(b.Except(a));
Run Code Online (Sandbox Code Playgroud)
或者你可以使用
var difference = new HashSet(a);
difference.SymmetricExceptWith(b);
Run Code Online (Sandbox Code Playgroud)
Cod*_*aos 11
此代码仅枚举每个序列一次,并用于Select(x => x)
隐藏结果以获得干净的Linq样式扩展方法.因为它使用HashSet<T>
它的运行时O(n + m)
是否散列很好.省略任一列表中的重复元素.
public static IEnumerable<T> SymmetricExcept<T>(this IEnumerable<T> seq1,
IEnumerable<T> seq2)
{
HashSet<T> hashSet = new HashSet<T>(seq1);
hashSet.SymmetricExceptWith(seq2);
return hashSet.Select(x => x);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
array1.NonIntersect(array2);
Linq 中不存在非相交这样的运算符,您应该这样做
例外 -> 联合 -> 例外
a.except(b).union(b.Except(a));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
101334 次 |
最近记录: |