views:

28

answers:

1

I have the following code that simply loops looking for a condition and places all matches into a new collection:

ObservableCollection<Device> allDevices = GetAllDevices();
ObservableCollection<Device> matchingDevices = new ObservableCollection<Device>();
foreach (Device device in allDevices )
{
    if (device.ID != 5)
        matchingDevices .Add(device);
}

Pretty simple. I tried to convert this into a Lambda statement in conjunction with Linq extention methods, but it's failing:

var matchingDevices = (ObservableCollection<Device>)allDevices.Where(d => d.ID != 5); 

This fails because it can't do the cast. I tried appending .ToList(), but same problem occurred. It sounds like this should be simple, but I can't find the answer.

+1  A: 
var matchingDevices = new ObservableCollection<Device>(allDevices.Where(d => d.ID != 5));

ObservableCollection has a constructor that takes an IEnumerable and that's what your Where clause is giving you.

Hightechrider