Remove object from generic list by id(按 id 从通用列表中删除对象)
问题描述
我有一个这样的域类:
public class DomainClass
{
public virtual string name{get;set;}
public virtual IList<Note> Notes{get;set;}
}
我将如何从 IList<Note> 中删除一个项目?如果它是一个 List,我将能够做到这一点,但它必须是一个 IList,因为我使用 Nhibernate 作为我的持久层.
How would I go about removing an item from the IList<Note>? I would be able to do it if it was a List but it has to be an IList as I am using Nhibernate for my persistance layer.
理想情况下,我希望在我的域类中使用这样的方法:
Ideally I wanted a method like this in my domain class:
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)
});
}
但我不能将 IList 转换为 List.有没有更优雅的方法来解决这个问题?
But I can't cast the IList as a List. Is there a more elegant way round this?
推荐答案
您可以过滤掉您不想要的项目并创建一个仅包含您想要的项目的新列表:
You could filter out the items you don't want and create a new list with only the items you do want:
public virtual void RemoveNote(int id)
{
//remove the note from the list here
Notes = Notes.Where(note => note.Id != id).ToList();
}
这篇关于按 id 从通用列表中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按 id 从通用列表中删除对象
基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
