给定以下两个字符串:
Dim str1() As String = {"123", "456", "789", "0"}
Dim str2() As String = {"123", "456", "1"}
如何执行 str1 和 str2 的完全外连接并最终得到如下结构:
{Nothing, "1"}
{"0", Nothing}
{"123", "123"}
{"456", "456"}
{"789", Nothing}
基于 SO 和其他网站上的一些讨论,我尝试使用 LINQ:
Dim v = From a In str1 Join b In str2 On a Equals b Group By a Into g = Group
From o In g.DefaultIfEmpty()
但它并没有产生想要的结果,这与这个(常规的 INNER JOIN)完全一样:
Dim v = From a In str1 Join b In str2 On a Equals b
我看到的最后一个示例是 here (C#)。
这里是 Another article ,但它似乎太复杂了,不可能成为最短的解决方案(我见过更简单的 C# 示例,希望 VB 也能同样高效)。
为什么这个问题有用
例如,可以有一个文件结构,其中文件路径是一个键。通过对键进行完全外部连接,您可以比较文件夹,找出哪一侧缺少哪些文件,并向用户显示差异。任何类型的同步任务都可以使用这种方法。
最佳答案
我想这不是您想要的解决方案,但它似乎可以完成任务:
string[] a1 = { "123", "456", "1" };
string[] a2 = { "123", "456", "789", "0" };
var intersection = a1.Intersect(a2); //get the intersection
var exceptions1 = a1.Except(a2); //get items from a1, that are not in a2
var exceptions2 = a2.Except(a1); //get items from a2, that are not in a1
var result = new List<Tuple<string, string>>(); //the result set
result.AddRange(intersection.Select(s => new Tuple<string, string>(s, s)));
result.AddRange(exceptions1.Select(s => new Tuple<string, string>(s, null)));
result.AddRange(exceptions2.Select(s => new Tuple<string, string>(null, s)));
foreach (var t in result)
{
Console.WriteLine((t.Item1 ?? "null") + "\t" + (t.Item2 ?? "null"));
}
输出是:
123 123
456 456
1 null
null 789
null 0
关于c# - 两个字符串数组的完全外连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14391109/