Microsoft Visual Studio – ASP.Net Using LINQ to Filter Collections

You have a collection of objects. You want a subset of that collection. Instead of making another SQL call to the database or using programming code to create a filtered subset of your original collection, you can accomplish this simply by using LINQ.

The following scenario has already a GridView full of address data. I placed a radiobuttonlist control below the grid that allows a user to select ‘ALL’ or ‘FL’ (Florida). When the user clicks ‘FL’, I want to display in the GridView a subset of the original collection that contains addresses that pertain to Florida only.

The following event for the RadioButtonList demonstrates creating the filtered subset by using LINQ.

    
Protected Sub RadioButtonList1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles RadioButtonList1.SelectedIndexChanged
        mNameAddressCollection = ViewState("DataSource")
        If IsNothing(mNameAddressCollection) = True Then
            Exit Sub
        End If

        Try
            If RadioButtonList1.SelectedValue.ToUpper = "ALL" Then
                GridView1.DataSource = mNameAddressCollection
                GridView1.DataBind()
            Else
                Dim newCollection = (From m As clsNameAddress In mNameAddressCollection Where m.State.ToUpper = "FL" Select m)
                GridView1.DataSource = newCollection.Cast(Of clsNameAddress).ToList
            End If

            GridView1.DataBind()
            txtRecordCount.Text = GridView1.DataSource.count

        Catch ex As Exception
            mLogger.Error(ex.Message)
        End Try
End Sub

The actual line of LINQ code from the event above:

Dim newCollection = (From m As clsNameAddress In mNameAddressCollection Where m.State.ToUpper = “FL” Select m)

You then need to cast the new collection and assign it to the datasource of the GridView:

GridView1.DataSource = newCollection.Cast(Of clsNameAddress).ToList

Leave a Reply

Your email address will not be published. Required fields are marked *