根据id从通用列表中移除对象

11 浏览
0 Comments

根据id从通用列表中移除对象

我有一个类似这样的领域类:

public class DomainClass
{
  public virtual string name{get;set;}
  public virtual IList Notes{get;set;}
}

我该如何从IList中移除一个项目?如果它是一个List,我可以做到,但由于我在持久层中使用Nhibernate,所以它必须是一个IList

理想情况下,我希望在我的领域类中有一个像这样的方法:

public virtual void RemoveNote(int id)
{
   //在这里从列表中移除注释
   List notes = (List)Notes
   notes.RemoveAll(delegate (Note note)
   {
       return (note.Id = id)
   });
}

但我无法将IList转换为List。有没有更优雅的方法解决这个问题?

0
0 Comments

问题的原因是在迭代列表时从列表中删除对象会导致异常。解决方法是使用ToList()方法将列表转换为一个新的列表,然后再进行迭代和删除操作。

代码实现的解决方法如下:

foreach (var n in Notes.Where(note => note.Id == id).ToList())
{
    Notes.Remove(n);
}

或者可以简化为:

Notes.Remove(Notes.First(note => note.Id == id));

第一个方法是最好的方法,因为它不会抛出异常。第二个方法如果列表中没有符合条件的对象会抛出异常。

注意:在使用这些方法之前,需要确保Notes列表已经初始化并且包含要删除的对象。

0
0 Comments

问题的出现原因是:在一个通用列表中,需要根据ID来移除对象。通用列表是一种不限制元素类型的数据结构,因此无法直接通过ID来移除对象。

解决方法是:改变数据结构,使用一个字典(Dictionary)来存储数据。字典是一种键值对的数据结构,可以通过键(ID)来快速查找和操作对象。通过将对象的ID作为键,对象本身作为值,可以方便地根据ID来移除对象。

代码示例:

public class DomainClass
{
  public virtual string name{get;set;}
  public virtual IDictionary Notes {get; set;}
  
  //Helper property to get the notes in the dictionary
  public IEnumerable AllNotes
  {
    get
    {
      return notes.Select (n => n.Value);
    }
  }
  
  public virtual void RemoveNote(int id)
  {
     Notes.Remove(id);
  }
}

如果ID不唯一,可以使用`IDictionary>`来替代字典。这样,每个ID对应的值是一个列表,可以存储多个对象。

以上就是从给定的内容中整理出的“Remove object from generic list by id”问题的出现原因和解决方法。通过改变数据结构,使用字典来存储对象,并提供移除对象的方法,可以方便地根据ID来移除对象。

0
0 Comments

问题的原因是需要从一个泛型列表中根据id删除对象。解决方法是通过过滤掉不需要的项并创建一个只包含需要项的新列表。具体的实现代码如下:

public virtual void RemoveNote(int id)
{
   //remove the note from the list here
   Notes = Notes.Where(note => note.Id != id).ToList();
}

另外,有人问到这种方法的效率如何。回答是这种方法的效率应该不会有太大差别,因为无论如何都需要遍历整个列表。

0