来自两个列表的不同列表(字符串)

Distinct List(Of String) from two Lists

我有两个 List(Of String),名为 MethodCodesMethodDescriptions。我想创造独特的价值。

例如我在列表中有这些值...

MethodCodes (45, 45, 46a, 46b, 47, 47)

MethodDescriptions (meth45, meth45, meth46, meth46, meth47, meth47)

我需要将此列表缩减为...

MethodCodes (45, 46a, 46b, 47)

MethodDescriptions (meth45, meth46, meth46, meth47)

实际上,唯一性必须是 MethodCodes 列表中的值,但两个列表中的项目数必须相同。

托马斯

也许这比它需要的更复杂,但由于你有成对的项目,我可能会先将它们组合起来 (Zip) 并找到不同的对,然后再将它们分开。

Dim MethodCodes = New List(Of String)() From {"45", "45", "46a", "46b", "47", "47"}
Dim MethodDescriptions = New List(Of String)() From {"meth45", "meth45", "meth46", "meth46", "meth47", "meth47"}
' Combine the two lists, and find the distinct pairs
Dim zipped = MethodCodes.Zip(MethodDescriptions, Function(a, b) Tuple.Create(a, b)).Distinct().ToList()
' Split the values up again
MethodCodes = zipped.Select(Function(x) x.Item1).ToList()
MethodDescriptions = zipped.Select(Function(x) x.Item2).ToList()

如果您有具有不同值的相同密钥(例如 47 - meth47a、47 - meth47b),那么这将保留两者,这可能不是您想要的 ("the unique must be values in MethodCodes list")。

如果这两个列表中的值有关联,那么最好保持它们在适当的数据结构中关联,例如class .

一个简单的 class 就可以做到:

Private Class Method
    Public Property Code As String
    Public Property Description As String
    Public Sub New(code As String, description As String)
        Me.Code = code
        Me.Description = description
    End Sub
End Class

这允许您像这样添加值:

Dim methods As New List(Of Method)
methods.Add(New Method("45", "meth45"))
methods.Add(New Method("45", "meth45"))
methods.Add(New Method("46a", "meth46"))
methods.Add(New Method("46b", "meth46"))
methods.Add(New Method("47", "meth47"))
methods.Add(New Method("47", "meth47"))

然后找到不同的代码值和相关的描述,如下所示:

For Each distinctMethod In methods.Distinct.GroupBy(Function(x) x.Code).Select(Function(d) d.First()).ToList()
    Debug.WriteLine(distinctMethod.Code & "-" & distinctMethod.Description)
Next

输出:

45-meth45
46a-meth46
46b-meth46
47-meth47