我有两个包含一组名称的字符串列表,我想知道的是如何比较这两个列表以查找相同的名称,然后编写一个if语句,根据比较执行操作。
清单1: 菲利普 短发 迈克尔
清单2: 詹姆士 彼得 鲍勃
答案 0 :(得分:5)
许多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 :(得分:1)
第一次写VB。您可以使用下面的嵌套循环来查找相同的循环。如果你想要大小写,请将equalsIgnoreCase替换为equals
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
答案 2 :(得分:1)
这可能会有所帮助
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
答案 3 :(得分:0)
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
输出将包含所有相同的名称和&匹配数量: Ziggy Bob Michael James& 4