通过标识删除常规列表中的对象

我有这样一个域类:


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


如何从中删除项目
IList<note>

? 如果是列表,我可以做到,但他应该是
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/
}/;
}


但我不能使用
IList

作为
List

. 是否有更优雅的方式来解决它?
</note></note></note></note>
已邀请:

知食

赞同来自:

您可以过滤耗尽不必要的项目,并仅使用所需的元素创建新列表:


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

Notes = Notes.Where/note => note.Id != id/.ToList//;
}

裸奔

赞同来自:

Edit2: 这种方法不需要带来

List


!


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


或者...


Notes.Remove/Notes.Where/note => note.Id == id/.First///;


第一的 - 最好的。

如果没有一个音符,第二个将导致例外情况
id

.

编辑:感谢Magnus和Rsbarro来展示我的错误。

三叔

赞同来自:

您可以手动对其进行编码。 天真的实施是 O/n*k/ 在列表中的n个项目和要删除的项目的k个项目。 如果你想简单地删除一个项目,它很快。

但如果你想删除许多项目,那么本机实现变成了
O/n^2/

对于许多实现
IList<t>

/包括
List<t>

, 我不知道该列表的行为 NHibernate/, 而且你需要写一点更多的代码来实现实现
O/n/


RemoveAll

.

来自旧答案的可能实现之一:
https://coderoad.ru/4086772/
这种实施的狡猾是 in 将保存项目移动到列表的顶部 O/n/. 然后他继续删除列表的最后一个元素/这通常是平等的 O/1/, 由于没有项目应该导航/, 所以截断变成了 o /n/ 满的。 这意味着整个算法是相等的 O /n/.
</t></t>

风见雨下

赞同来自:

如果可以更改数据结构,我会建议使用
Dictionary

. 你能和什么能做些什么:


public class DomainClass
{
public virtual string name{get;set;}
public virtual IDictionary<int, note=""> Notes {get; set;}

//Helper property to get the notes in the dictionary
public IEnumerable<note> AllNotes
{
get
{
return notes.Select /n =&gt; n.Value/;
}
}

public virtual void RemoveNote/int id/
{
Notes.Remove/id/;
}


}

如果一个 ID 不是唯一的,使用
IDictionary<int, ilist<note="">&gt;

.
</int,></note></int,>

卫东

赞同来自:

请注意,在某些情况下,最好避免

公共虚拟人

, 使用
http://en.wikipedia.org/wiki/T ... ttern
pattern 因此:


public void Load/IExecutionContext context/ 
{
// Can safely set properties, call methods, add events, etc...
this.Load/context/;
// Can safely set properties, call methods, add events, etc.
}

protected virtual void Load/IExecutionContext context/
{
}

风见雨下

赞同来自:

您可以获得要删除的一系列元素。 如何从周期中的列表中删除它们。
看看这个样本:


IList<int> list = new List<int> { 1, 2, 3, 4, 5, 1, 3, 5 };

var valuesToRemove = list.Where/i =&gt; i == 1/.ToArray//;

foreach /var item in valuesToRemove/
{
list.Remove/item/;
}


</int></int>

要回复问题请先登录注册