如何确定数组中是否存在重复值

时间:2016-08-05 18:23:24

标签: vb.net

我要做的是使用5个文本框从用户那里获取一个数字输入,然后将这些数字放在一个数组中。

我如何确定值是否在数组中重复?就像阵列最终是: {2,3,2,8,4} 我不确定如何让程序基本上说“有2个文本框的值为2。”

感谢。

2 个答案:

答案 0 :(得分:1)

以下是一个使用LINQ的简单示例:

Sub Main()
   Dim myArray As Integer() = {2, 3, 2, 8, 4}

   For Each group In myArray _
      .GroupBy(Function(i) i) _
      .Where(Function(grp) grp.Count > 1)

      Console.WriteLine($"There are {group.Count} textboxes with the value {group.Key}.")
   Next
End Sub

答案 1 :(得分:-1)

假设两个数组的类型相同,这应该可以解决问题:

Dim hasDupes As Boolean
Dim array1 As Integer() = {3, 5, 7, 11, 13}
Dim array2 As Integer() = {1, 3, 5, 7, 9, 11, 13}

hasDupes = array1.Intersect(array2).Any()

如果有任何重复的项目,hasDupes将评估为true。