【问题标题】:Duplicate value in lists. How can I avoid it?列表中的重复值。我怎样才能避免它?
【发布时间】:2019-01-07 14:57:38
【问题描述】:
Public Class clsA   
    Public icounter As Integer
    Public dtime As DateTime 
End Class

Dim list_A As New List(Of clsA)

Dim dyus As DateTime = DateTime.Now
oB = New clsA
oB.dtime = dyus
oB.counter = counter2 (comes from COM Port)

Dim b As Integer = oB.counter

Dim t1 As TimeSpan = New TimeSpan(0, 1, 0)

list_A.Add(oB)


If DateTime.Now - (list_A(0).dtime) > t1 Then
    If list_A.Sum(Function(x) x.counter) > 10 Then
        MessageBox.Show("TEST")
    End If
End If

你好,

list_A.Add(oB) 有 2 个值,dtime (DateTime) 和 icounter (Integer)。

list_A 在计时器中。所以它总是增加,但我想避免在这个列表中出现重复的计数器。

我该怎么做?

输出是:

time 1/7/2019 06:10:16 PM
counter 0

time 1/7/2019 06:10:18 PM
counter 0

time 1/7/2019 06:10:20 PM
counter 1

time 1/7/2019 06:10:20 PM
counter 1

我想要输出:

time 1/7/2019 06:10:16 PM
counter 0

time 1/7/2019 06:10:20 PM
counter 1

不应添加(或删除)带有计数器的重复项。

【问题讨论】:

  • 这不是 C#。这是 VB 或 VBA。
  • @Adriani6 ,我确定他们的意思是My issue is still the same, despite the language being different
  • @kegnonegni ,您能否添加一个您当前输出的示例以及您的预期/期望输出的示例?
  • 好吧,也许如果您在添加之前检查列表是否包含该元素,它将消除重复项。通过引用或利用 Equals 方法。
  • 如果您想避免集合中的重复,请使用HashSet 而不是List。请务必在使用之前阅读有关 HashSet(Of T) 类的所有信息。不要只是假设它会以特定的方式工作。

标签: vb.net list winforms


【解决方案1】:

您可以像这样遍历所有这些:

'New list
Dim list_B As New List(Of clsA)
For each item in list_A
    If Not list_B.Contains(item) Then
        list_B.Add(item)
    End If
Next

如果您在最后执行此操作,您应该有一个名为 list_B 的新列表,其中包含所有列出的所有内容,但没有重复

【讨论】:

    猜你喜欢
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 2022-12-08
    相关资源
    最近更新 更多