Remove object from generic list by id

前端 未结 6 1418
你的背包
你的背包 2021-02-07 10:50

I have a domain class like this:

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


        
6条回答
  •  臣服心动
    2021-02-07 11:39

    Edit2: This method doesn't require casting to a List!

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

    or...

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

    The first one is the best.
    The second one will throw an exception if no notes have that id.

    Edit: Thanks to Magnus and rsbarro for showing my mistake.

提交回复
热议问题