[英]Removing an item from a list - C#
I have rather a complex datastructure.我有一个相当复杂的数据结构。 The simple version looks like this:
简单版本如下所示:
public class Field
{
List<FieldRow> fieldRow;
//I want to write a delete that iterates and deletes given the key
//(Use Linq?)
public void DeleteByKey(int key)
{
//Do Remove
}
}
public class FieldRow
{
public int key;
}
Any help in implementing Delete is appreciated.感谢您在实施删除方面的任何帮助。
public class Field
{
List<FieldRow> fieldRow;
public void DeleteByKey(int key)
{
fieldRow.RemoveAll(row => key == row.key);
}
}
public class FieldRow
{
public int key;
}
List<T>().RemoveAll()
will do what you want. List<T>().RemoveAll()
会做你想做的事。
You give it a Predicate delegate type, that is executed for each item, like a where clause:你给它一个 Predicate 委托类型,它为每个项目执行,就像一个 where 子句:
fieldRow.RemoveAll(item => item.Key == key);
However, you might want to consider storing the data in a Dictionary<int, FieldRow>
.但是,您可能需要考虑将数据存储在
Dictionary<int, FieldRow>
中。 That way you can access the dictionary/map directly by key.这样您就可以直接按键访问字典/地图。 This would improve performance.
这将提高性能。
You could find the index of the field you need to remove and use the RemoveAt method on List.您可以找到需要删除的字段的索引,并在 List 上使用 RemoveAt 方法。
I will add an example in a minute.
我将在一分钟内添加一个示例。
Nevermind, the suggestion to use RemoveAll with a predicate seems to be a better option:-)没关系,将 RemoveAll 与谓词一起使用的建议似乎是一个更好的选择:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.