【发布时间】:2016-03-04 00:31:30
【问题描述】:
我有两个包含一组名称的字符串列表,我想知道如何比较这两个列表以找到相同的名称,然后编写一个 if 语句根据比较执行操作。
清单 1: 菲利普 鲍勃 迈克尔
清单 2: 詹姆士 彼得 鲍勃
【问题讨论】:
我有两个包含一组名称的字符串列表,我想知道如何比较这两个列表以找到相同的名称,然后编写一个 if 语句根据比较执行操作。
清单 1: 菲利普 鲍勃 迈克尔
清单 2: 詹姆士 彼得 鲍勃
【问题讨论】:
许多 linq 扩展之一是 Intersect,它返回两者共有的元素:
Dim names1 = {"Philip", "Bob", "Michael"}
Dim names2 = {"James", "Ziggy", "Bob", "Hoover"}
Dim commonNames = names1.Intersect(names2).ToArray()
For Each n As String In commonNames
Console.WriteLine(n)
Next
输出:
鲍勃
其中有很多,您可以输入 .(点)并通过 Intellisense 浏览它们并阅读它们所做的 1-liner 并至少意识到它们的存在。
【讨论】:
这可能会有所帮助
lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase)
PrintList(lstNew)
Console.ReadLine()
End Sub
Private Sub PrintList(ByVal str As IEnumerable(Of String))
For Each s In str
Console.WriteLine(s)
Next s
Console.WriteLine("-------------")
参考 http://www.devcurry.com/2010/07/list-common-elements-between-two-list.html?m=1
【讨论】:
第一次写VB。您可以使用下面的嵌套循环来查找相同的。如果您希望大小写重要,请将 equalsIgnoreCase 替换为仅等于
Dim list1() as String ={"name1","name2"}
Dim list2() as String ={"name3","name2"}
For Each str as String In list1
For Each names as String In list2
If String.Compare(str,names) = 0 Then
Console.WriteLine(str+" "+names)
End If
Next names
Next str
【讨论】:
Dim names1 = {"Philip", "Ziggy", "Bob", "Michael", "James"}
Dim names2 = {"James", "Ziggy", "Bob", "Michael", "Hoover"}
Dim commonNames = names1.Intersect(names2).ToArray()
Dim Match As String = ""
Dim NumberOfMatches = 0
For Each n As String In commonNames
Match += n.ToString + " "
NumberOfMatches += 1
Next
TextBox1.Text = Match
TextBox2.Text = NumberOfMatches
输出将包含所有相同的名称和匹配数: 齐吉鲍勃迈克尔詹姆斯 & 4
【讨论】: