vb.net - 为什么 LINQ 中的 Union 函数不删除重复条目?

标签 vb.net linq union

我正在使用 VB .NET,并且我知道 Union 通常按 ByRef 工作,但在 VB 中,字符串通常被视为原始数据类型。

因此,问题来了:

Sub Main()
    Dim firstFile, secondFile As String(), resultingFile As New StringBuilder

    firstFile = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.Desktop & "\1.txt").Split(vbNewLine)
    secondFile = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.Desktop & "\2.txt").Split(vbNewLine)

    For Each line As String In firstFile.Union(secondFile)
        resultingFile.AppendLine(line)
    Next

    My.Computer.FileSystem.WriteAllText(My.Computer.FileSystem.SpecialDirectories.Desktop & "\merged.txt", resultingFile.ToString, True)
End Sub

1.txt包含:
一个
b
c
d

2.txt包含:
b
c
d
电子
f

h

j

运行代码后,我得到:
一个
b
c
d
电子
b
f

h

j

对于使 Union 函数像其数学对应函数一样工作,有什么建议吗?

最佳答案

Linq Union 确实按照您想要的方式执行。确保您的输入文件正确(例如,其中一行在换行符之前可能包含空格)或 Trim() 分割后的字符串?

var list1 = new[] { "a", "s", "d" };
var list2 = new[] { "d", "a", "f", "123" };
var union = list1.Union(list2);
union.Dump(); // this is a LinqPad method

linqpad ,结果为 {"a", "s", "d", "f", "123"}

关于vb.net - 为什么 LINQ 中的 Union 函数不删除重复条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1250588/

相关文章:

c# - LINQ:根据最大值从对象列表中进行分组和选择

sql - MS Access 在所有列中循环联合查询?

mysql - 使用 UNION ALL 进行慢速查询

vb.net - VB.NET调用方法

vb.net - 在模拟用户下运行的非 UI 线程是否会自动模拟 UI 线程?

.net - Task.Wait 不等待

c# - GroupJoin by date where date in second list between two dates from first

c# - 如何从在 asp.net 中用 scriptmanager.registerclientscript 编写的 javascript 确认框返回值?

c# - 在 Linq to NHibernate 中测试条件的最佳方法是什么?

php - 如何将 3 个不同数据库的 3 个数据库表合并到数据库 4 中