.NET Tips and Tricks

Blog archive

Using LINQ with Collections That Don't Support LINQ

I've been working on a Windows Forms application for one of my clients and, in the application, I use the CheckedBoxList and the DataGridView. Both of them have really useful collections: the CheckedBoxList has a CheckedItems collection that holds all the items that the user has checked, and the DataGridView has a SelectedRows collection that holds all the rows the user's selected, for instance. The CheckedItems collection can hold any object I want while the SelectedRows collection holds DataGridViewRow objects.

The problem is that neither of these collections will work with LINQ.

Fortunately, rather than use For…Each loops, I can use the OfType method to convert these collections into something that will work with LINQ. All I have to do is pass the OfType method the object type held in the collection. For instance, to use LINQ with the DataGridView's SelectedRows collection, I use this code; it converts the DataItem property for each row into the object associated with each row:

 
Dim coll = From rw In  Me.gvInvoices.SelectedRows.OfType(Of DataGridViewRow)()
Select CType(rw.DataBoundItem,  ClaimCededDetailClass

The following code processes the ClaimHeaderClass objects I hold in my CheckedBoxList, and hands back those object that have their AuthorizationLevel property set to "High":

Dim cc  = cblClaims.CheckedItems.OfType(Of ClaimHeaderClass).
Where(Function(chc) chc.AuthorizationLevel = "High")
But wait, there's more! I have a Panel on the form with a set of RadioButtons in it. The Panel, of course, has a Controls collection that holds all of those RadioButtons. This code converts that collection into a LINQ-compatible collection of RadioButtons, then lets me find the name of the RadioButton the user selected:

strRadio = (From rb In  Me.plStatusRadio.Controls.OfType(Of RadioButton)()
Where rb.Checked
Select rb.Name).FirstOrDefault

Posted by Peter Vogel on 11/15/2013


comments powered by Disqus

Featured

Subscribe on YouTube