从通用列表中获取对称差异

我有2个单独的List,我需要比较两个并获得除两个列表的交集之外的所有内容。 我该怎么做(C#)?

你可以使用Except来获取除两个列表的交集 之外的所有内容。

var differences = listA.Except(listB).Union(listB.Except(listA)); 

如果你想获得除工会之外的所有东西:

 var allButUnion = new List(); 

(联盟是两个列表中的所有东西 – 除了联合之外的所有东西都是空集…)

如果你的意思是除了交集(对称差异)之外的一切,你可以尝试:

 var set = new HashSet(list1); set.SymmetricExceptWith(list2); 

你的意思是只列在一个列表中的所有内容吗? 怎么样:

 var allButIntersection = a.Union(b).Except(a.Intersect(b)); 

这可能有点低效,但它只是简单地表明了你的意思(假设我当然正确地解释了你)。

像这样的东西?

 String[] one = new String[] { "Merry", "Metal", "Median", "Medium", "Malfunction", "Mean", "Measure", "Melt", "Merit", "Metaphysical", "Mental", "Menial", "Mend", "Find" }; String[] two = new String[] { "Merry", "Metal", "Find", "Puncture", "Revise", "Clamp", "Menial" }; List tmp = one.Except(two).ToList(); tmp.AddRange(two.Except(one)); String[] result = tmp.ToArray(); 

这是一个通用的扩展方法。 Rosetta Code使用Concat,而Djeefther Souza表示它更有效率。

 public static class LINQSetExtensions { // Made aware of the name for this from Swift // https://stackoverflow.com/questions/1683147/get-the-symmetric-difference-from-generic-lists // Generic implementation adapted from https://www.rosettacode.org/wiki/Symmetric_difference public static IEnumerable SymmetricDifference(this IEnumerable first, IEnumerable second) { // I've used Union in the past, but I suppose Concat works. // No idea if they perform differently. return first.Except(second).Concat(second.Except(first)); } } 

我实际上没有对它进行基准测试。 我认为这将取决于Union vs. Concat的实施方式。 在我的梦幻世界中,.NET根据数据类型或集合大小使用不同的算法,但对于IEnumerable,它无法提前确定集合大小。

此外,你几乎可以忽略我的回答 – Jon Skeet说HashSet方法“非常好 – 看起来这对我来说是最好的方式。”

 var theUnion = list1.Concat(list2); var theIntersection = list1.Intersect(list2); var theSymmetricDifference = theUnion.Except(theIntersection); 

使用除外:

 List l1 = new List(new[] { 1, 2, 3, 4 }); List l2 = new List(new[] { 2, 4 }); var l3 = l1.Except(l2);