通过id从通用列表中删除对象

gdp*_*gdp 14 c# generics compare list

我有这样的域类:

public class DomainClass
{
  public virtual string name{get;set;}
  public virtual IList<Note> Notes{get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我该如何从中删除项目IList<Note>?如果它是一个List我可以做到,但它必须是一个,IList因为我使用Nhibernate作为我的持久层.

理想情况下,我想在我的域类中使用这样的方法:

public virtual void RemoveNote(int id)
{
   //remove the note from the list here

   List<Note> notes = (List<Note>)Notes

   notes.RemoveAll(delegate (Note note)
   {
       return (note.Id = id)
   });
}
Run Code Online (Sandbox Code Playgroud)

但我不能把它IList作为一个List.这周围有更优雅的方式吗?

Gab*_*abe 31

您可以过滤掉您不想要的项目,并创建一个仅包含您想要的项目的新列表:

public virtual void RemoveNote(int id)
{
   //remove the note from the list here

   Notes = Notes.Where(note => note.Id != id).ToList();
}
Run Code Online (Sandbox Code Playgroud)


Ver*_*cas 11

Edit2:这个方法不需要强制转换为 List!

foreach (var n in Notes.Where(note => note.Id == id).ToArray()) Notes.Remove(n);
Run Code Online (Sandbox Code Playgroud)

要么...

Notes.Remove(Notes.Where(note => note.Id == id).First());
Run Code Online (Sandbox Code Playgroud)

第一个是最好的.
如果没有注释,第二个将抛出异常id.

编辑:感谢Magnus和rsbarro显示我的错误.

  • 在迭代它时从列表中删除项目,不会工作.做一个`.ToList()` (4认同)
  • @Magnus是对的,第一个会抛出一个`InvalidOperationException:Collection被修改; 枚举操作可能无法执行. (2认同)