开发者

How to use Linq/Lambda with ObservableCollection<T>

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜