Have you ever created a ListView control and wanted to get the collection of items that the user has checked?  While I was working on my demo for MEDC, that was one of the things that I needed to be able to do.  If I were writing my application for the .NET Framework, I would get the collection of items via the ListView.CheckedItems property.  When I looked up ListView in the MSDN documentation, I found that the CheckedItems property is not supported on the .NET Compact Framework.  As a result, I was going to need to create the collection myself.  Or was I?

Since the application that I was writing was a demonstration of the cool new features of .NET Compact Framework version 3.5, I decided to try my hand a using Language Integrated Query, specifically LINQ to Objects.  The resulting code was small, worked well and was quite easy to read.  Let's take a look at what I wrote.

public static List<ListViewItem> GetCheckedListViewItems(ListView lv)
    List<ListViewItem> checkedItems = (from ListViewItem lvi in lv.Items
                                         where (true == lvi.Checked)
                                         select lvi).ToList();

    return checkedItems;

The method above is based on my Lunch Launcher demo application, as shown during the What's New in .NET Compact Framework version 3.5 session that I delivered at MEDC 2007 last month.   How does it work?  First, we specify that we are interested in the ListViewItem objects contained within the ListView.Items property.

from ListViewItem lvi in lv.Items

Next, we define the condition under which we are interested in the item, in our case when the item has been checked by the user.

where (true == lvi.Checked)

Then we select the item.

select lvi

Lastly, we call the ToList method to have the selected items returned to us as a List<ListViewItem>.

Pretty neat and much nicer to read than a foreach loop.  If you have installed the beta of .NET Compact Framework version 3.5, give LINQ a try and see how it can make your applications easier to write.

-- DK

[Edit: fix formatting]

This posting is provided "AS IS" with no warranties, and confers no rights.
The information contained within this post is in relation to beta software.  Any and all details are subject to change.