c# - 两个字符串数组的完全外连接

标签 c# vb.net linq .net-4.0 outer-join

给定以下两个字符串:

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/

相关文章:

c# - 笛卡尔积或 2 个大文本文件的最佳方法

sql - 检查重叠日期(vb.net)

c# - 如果中间发生页面更改,AJAX 请求/响应的数据会发生什么情况

.net - 解释一下这个功能可能会出现什么问题(如果有的话)

c# - 检查 LINQ 查询是否返回行

c# - 使用 LINQ(函数式编程)将列表缩减为两个较小的列表

c# - 使用 C/C++ 编写 DLL 以实现 .Net 互操作性

c# - 在 C# 中将未知参数/返回类型作为参数的传递方法

c# - 覆盖插件 NopCommerce 4.3 的 View

C# 跳过第一行但希望它跳过最后一行