【问题标题】:Using linq query on ObservableCollection of interface?在接口的 ObservableCollection 上使用 linq 查询?
【发布时间】: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&lt;MyClass&gt;,在 linq 查询中进行转换),但没有取得多大成功。

【问题讨论】:

  • MyClass mc = (MyClass)MyCollection.Where(x=&gt;x.Name=="SomeName").SingleOrDefault(); MyCollection.Remove(mc);
  • @MaciejLos 谢谢,但为什么这不能直接与Remove() 一起使用?
  • 因为Collection<T>.Remove(T) Method需要特定类型的项目而不是IEnumerable&lt;T&gt;
  • 谢谢,我想我现在明白了 :)

标签: c# linq interface observablecollection


【解决方案1】:

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

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

后续响应:

如果 MyClass 上的另一个属性不在接口上,则需要进行一些转换:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 2010-10-27
    • 1970-01-01
    • 2013-12-15
    相关资源
    最近更新 更多