简体   繁体   中英

Find and Insert into list class collection?

I have class called GroupSelect and made a collection List(Of GroupSelect)() .

Now I need to find GroupSelect with RowNo and GroupNo in List(Of GroupSelect)() . If I found at same index update Value . If not found add to 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

Find this Object in the colleaction

                grpSelect.RowNo = rowNo
                grpSelect.GroupNo = grpNo
                grpSelect.Value = CType(CType(row.FindControl("txtCombine"), 
TextBox).Text, Integer)

How to do this?

Assuming collection is your List(Of GroupSelect) and RowNo , GroupNo are the values you are checking againt and Value is the new 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() should be ideal in your case because it doesn't look like you will never have more than one item matching the criteria. But it might be a good idea to surround the query with with Try..Catch .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM