在接口的 ObservableCollection 上使用 linq 查询?

Using linq query on ObservableCollection of interface?

我有一个 class,它实现了一个接口:

class MyClass : IMyInterface
{
    public Name { get; set;}

    // bunch of other stuff...
}

在我的代码中,我想像这样从集合中删除一项:

ObservableCollection<IMyInterface> MyCollection = new ObservableCollection<IMyInterface>();
// fill collection and do some other stuff...

// Trying to remove one item based on the Name property of the object. 
// At this point I already know, that my collection of IMyInterface is actually a
// collection of MyClass
MyCollection.Remove(c => c.Name == "SomeName");

这给了我以下错误:

Cannot convert lambda expression to type 'IMyInterface' because it is not a delegate type

有没有办法在这样的接口集合上使用 linq 表达式?

后续问题:

万一 Name 属性 不存在于界面中(所以它只出现在 MyClass 中),实现上述目标的方法是什么?我用不同的转换进行了测试(将整个集合转换为 ObservableCollection<MyClass>,在 linq 查询中转换),但没有取得多大成功。

remove 方法需要 IMyInterface 类型的对象。 你应该这样删除一个项目:

MyCollection.Remove(MyCollection.FirstOrDefault(c => c.Name == "SomeName"));

Follow-Up 响应:

如果 MyClass 上有另一个不在界面上的 属性,您将需要进行一些转换:

var myClassCollection = MyCollection.ToList().ConvertAll(c => (MyClass)c);
var itemTobeRemove = myClassCollection.FirstOrDefault(c => c.OtheProp == "test");
MyCollection.Remove(itemTobeRemove);