为什么LINQ中的Union函数不能删除重复的条目? [英] Why doesn't the Union function in LINQ remove duplicate entries?
问题描述
我正在使用VB .NET,我知道Union通常可以使用ByRef,但是在VB中,字符串通常像原始数据类型一样进行处理.
I'm using VB .NET and I know that Union normally works ByRef but in VB, Strings are generally processed as if they were primitive datatypes.
因此,这就是问题所在:
Consequently, here's the problem:
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
1.txt contains:
a
b
c
d
e
2.txt包含:
b
c
d
e
f
g
h
我
j
2.txt contains:
b
c
d
e
f
g
h
i
j
运行代码后,我得到:
一个
b
c
d
e
b
f
g
h
我
j
After running the code, I get:
a
b
c
d
e
b
f
g
h
i
j
关于使Union函数像数学函数一样起作用的任何建议吗?
Any suggestions for making the Union function act like its mathematical counterpart?
推荐答案
Linq Union
确实可以达到预期的效果.确保输入文件正确(例如,其中一行可能在换行符之前包含空格)或拆分后的Trim()
字符串?
Linq Union
does perform as you want it to. Ensure your input files are correct (e.g. one of the lines may contain a space before the newline) or Trim()
the strings after splitting?
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" }
这篇关于为什么LINQ中的Union函数不能删除重复的条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!