vb.net索引列表的类

时间:2015-12-02 21:33:51

标签: vb.net list class indexof

我正在处理我正在处理的大量代码中的问题,因此我创建了一小段代码来显示问题。我创建了一个代表库存项目的类(stockstatus)。它们具有部件号(.part),数量(.qty)和成本(.cost)。我创建了该类的列表(ssr)来表示整个库存。我现在正在尝试搜索特定部件号的库存,但我遇到了麻烦。

如果我尝试使用ssr.IndexOf,它希望将stockstatus传递给IndexOf函数。如果我创建一个带有基础.part的stockstatus,我将其初始化为第二个零件号(“CP0065-10N-S”),则IndexOf函数始终返回-1。我认为.qty和.cost也必须匹配IndexOf才能返回正确的索引,但是我无法知道我正在处理的代码中的那些值。我需要能够找到一个完全基于搜索.part的索引。最简单的方法是什么?

Public Class stockstatus
    Public part As String
    Public qty As Double
    Public cost As Double
End Class

Public Partial Class MainForm

    Public ssr As New List(Of stockstatus)

    Public Sub New()
        Me.InitializeComponent()
    End Sub

    Sub MainFormLoad(sender As Object, e As EventArgs)
        ssr = getSSR()
        Dim ss As New stockstatus
        ss.part = "CP0065-10N-S"
        MsgBox(ssr.IndexOf(ss)) 'returns -1.  i want it to return index 1
    End Sub

    Public Function getSSR() As List(Of stockstatus)
        Dim s As New List(Of stockstatus)
        Dim ss As New stockstatus
        ss.part = "CP0065-0.1U-S"
        ss.qty = 1000.0R
        ss.cost = 0.001R
        s.Add(ss)
        ss.part = "CP0065-10N-S"
        ss.qty = 2000.0R
        ss.cost = 0.002R
        s.Add(ss)
        Return s
    End Function

End Class

1 个答案:

答案 0 :(得分:0)

感谢@Plutonix的帮助!

这里的代码正在运行:

Imports System.Linq

Public Class stockstatus
    Public part As String
    Public qty As Double
    Public cost As Double
End Class

Public Partial Class MainForm

    Public ssr As New List(Of stockstatus)

    Public Sub New()
        Me.InitializeComponent()
    End Sub

    Sub MainFormLoad(sender As Object, e As EventArgs)

        ssr = getSSR()
        Dim item As stockstatus = ssr.Where(Function(x) x.part = "CP0065-10N-S").FirstOrDefault
        If item IsNot Nothing Then
            Dim ndx As Integer = ssr.IndexOf(item)
            MsgBox(ndx)   'This works now.  It returns 1.
        End If

    End Sub

    Public Function getSSR() As List(Of stockstatus)
        Dim s As New List(Of stockstatus)
        Dim ss As New stockstatus
        ss.part = "CP0065-0.1U-S"
        ss.qty = 1000.0R
        ss.cost = 0.001R
        s.Add(ss)
        ss = New stockstatus
        ss.part = "CP0065-10N-S"
        ss.qty = 1000.0R
        ss.cost = 0.001R
        s.Add(ss)
        Return s
    End Function

End Class