相交可以用来查找匹配两个集合之间,像这样:
//指定两个数组。
INT [] ARRAY1 = {1,2,3};
INT [] ARRAY2 = {2,3,4};
//调用相交扩展方法。
VAR相交= array1.Intersect(ARRAY2);
//写路口画面。
的foreach(在相交int值)
{
Console.WriteLine(值); //输出:2,3
}
不过我想实现的是相反的,我想列出的是缺少项比较两个集合时:
//指定两个数组。
INT [] ARRAY1 = {1,2,3};
INT [] ARRAY2 = {2,3,4};
//调用相交扩展方法。
VAR相交= array1.NonIntersect(ARRAY2); //我做了NonIntersect方法
//写路口画面。
的foreach(在相交int值)
{
Console.WriteLine(值); //输出:4
}
解决方案
如前所述,如果你想获得4作为结果,你可以这样做:
VAR nonintersect = array2.Except(ARRAY1);
如果你想真正的无交集(还兼有1和4),那么这应该做的伎俩:
VAR nonintersect = array1.Except(ARRAY2).Union(array2.Except(ARRAY1));
这不会是最高效的解决方案,但对于小名单这应该只是罚款。
Intersect can be used to find matches between two collections, like so:
// 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
}
However what I'd like to achieve is the opposite, I'd like to list the items that are missing when comparing two collections:
// Assign two arrays.
int[] array1 = { 1, 2, 3 };
int[] array2 = { 2, 3, 4 };
// Call Intersect 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
}
解决方案
As stated, if you want to get 4 as the result, you can do like this:
var nonintersect = array2.Except(array1);
If you want the real non-intersection (also both 1 and 4), then this should do the trick:
var nonintersect = array1.Except(array2).Union( array2.Except(array1));
This will not be the most performant solution, but for small lists it should work just fine.
上一篇:我该如何重新present时间在.NET中唯一的价值?我该、价值、时间、present
下一篇:Parallel.ForEach()主场迎战的foreach(IEnumerable的< T> .AsParallel())主场、foreach、Parallel、ForEach