【发布时间】:2020-09-09 08:41:39
【问题描述】:
我有一个类,它实现了一个接口:
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");
这给了我以下错误:
无法将 lambda 表达式转换为类型“IMyInterface”,因为它不是委托类型
有没有办法在这样的接口集合上使用 linq 表达式?
后续问题:
如果接口中不存在Name 属性(所以它只出现在MyClass 中),实现上述目标的方法是什么?我测试了不同的演员表(将整个集合转换为ObservableCollection<MyClass>,在 linq 查询中进行转换),但没有取得多大成功。
【问题讨论】:
-
MyClass mc = (MyClass)MyCollection.Where(x=>x.Name=="SomeName").SingleOrDefault(); MyCollection.Remove(mc); -
@MaciejLos 谢谢,但为什么这不能直接与
Remove()一起使用? -
因为Collection<T>.Remove(T) Method需要特定类型的项目而不是
IEnumerable<T> -
谢谢,我想我现在明白了 :)
标签: c# linq interface observablecollection