查找并插入列表类集合?

时间:2011-03-10 01:44:33

标签: c# vb.net

我有一个名为GroupSelect的类,并创建了一个集合List(Of GroupSelect)()

现在,我需要在GroupSelect中找到RowNoGroupNo的{​​{1}}。如果我找到相同的索引更新List(Of GroupSelect)()。如果未找到,请添加到Value

List(Of GroupSelect)

在合作中找到此对象

Public Class GroupSelect
    Public Property RowNo() As Integer
        Get
            Return m_RowNo
        End Get
        Set(ByVal value As Integer)
            m_RowNo = value
        End Set
    End Property
    Private m_RowNo As Integer
    Public Property GroupNo() As Integer
        Get
            Return m_GroupNo
        End Get
        Set(ByVal value As Integer)
            m_GroupNo = value
        End Set
    End Property
    Private m_GroupNo As Integer

    Private m_Value As Integer
    Public Property Value() As Integer
        Get
            Return m_Value
        End Get
        Set(ByVal value As Integer)
            m_Value = value
        End Set
    End Property

End Class

怎么做?

1 个答案:

答案 0 :(得分:0)

假设收集是您的List(Of GroupSelect)RowNoGroupNo是您要检查的值,Value是新值

Dim item As GroupSelect = collection.Where(Function(i) i.RowNo = RowNo AndAlso i.GroupNo = GroupNo).SingleOrDefault()

If item Is Nothing Then
    Dim newItem As New GroupSelect()
    newItem.GroupNo = GroupNo
    newItem.RowNo = RowNo

    newItem.Value = Value

    collection.Add(newItem)
Else
    item.Value = Value
End If

SingleOrDefault()在您的情况下应该是理想的,因为它看起来不会有多个符合条件的项目。但用Try..Catch围绕查询可能是个好主意。