如何从号码列表中找到唯一/不同的号码

时间:2019-06-08 19:15:57

标签: vb.net

我有一个数字列表,范围为1到5位数字(数字是DataGridView列中的值)。只有唯一的数字之一。所有其他数字至少重复一次。我需要得到一个唯一的号码,不能重复。

在线上有很多不错的文章可以满足我的任务,有些文章使用linq,但没有一篇寻找唯一的文章。我找到了下面显示的代码,但我不明白Function(X)是什么。

Dim distinct = mynumber.DistinctBy(Function(X) X.muNumber).ToList

1 个答案:

答案 0 :(得分:0)

我在数字列表上使用了Linq查询,并在查询上使用了.ToList,因此它可以生成更友好的List(Of Integer),而不是IEnumerable。由于您似乎确定只有一个唯一值,因此将列表的第一项打印到立即窗口中。如果要获得更多唯一值,则可以遍历唯一值。

我确信这不是执行此操作的最有效方法,但它应该可以工作。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim lstNumbers As New List(Of Integer) From {1, 5, 77, 1, 32, 5, 77}

    Dim unique = (From i In lstNumbers
                  Let ct = (From i2 In lstNumbers Where i2 = i Select i2).Count
                  Where ct = 1
                  Select i).ToList

    Debug.Print(unique(0).ToString)
End Sub

编辑 根据OP的评论-如何使用数字字符串。

    'This line won't compile unless you put quotes around it.
    Dim nums As String = "1,2, 3, 4, 1, 2, 3, 4, 5"
    'There are a few steps to change this string into a list of numbers.
    'First get an array of strings
    Dim splitNums = nums.Split(","c) 'This overload of Split takes a Char array. The c tells it that this is a char not a string.
    'Each of the strings in the array are trimmed of any leading or trailing spaces.
    'Then the string is converted to an Integer
    'Finally the whole query is changed to a list
    Dim lstNumbers = (From i In splitNums
                      Select CInt(i.Trim)).ToList
    'and now lstNumbers is indeed a list of Integers which can be used in the code.

编辑2

要查看是否有多个唯一数字,请使用For Each循环。

    For Each i In unique
        TextBox1.Text &= i.ToString & ", "
    Next