如何从C#列表中删除项目? [英] How to remove item from list in C#?
问题描述
我有一个存储在结果列表中的列表,如下所示:
I have a list stored in resultlist as follows:
var resultlist = results.ToList();
它看起来像这样:
ID FirstName LastName
-- --------- --------
1 Bill Smith
2 John Wilson
3 Doug Berg
如何从列表中删除ID 2?
How do I remove ID 2 from the list?
推荐答案
List<T>
有两种可以使用的方法.
List<T>
has two methods you can use.
RemoveAt(int index),可以使用项目的索引.例如:
RemoveAt(int index) can be used if you know the index of the item. For example:
resultlist.RemoveAt(1);
或者您可以使用删除(T项):>
Or you can use Remove(T item):
var itemToRemove = resultlist.Single(r => r.Id == 2);
resultList.Remove(itemToRemove);
如果不确定项目是否确实存在,可以使用 SingleOrDefault .如果没有项目,则SingleOrDefault
将返回null
(Single
在找不到该项目时将引发异常).当存在重复值(两个具有相同id
的项)时,两者都将抛出.
When you are not sure the item really exists you can use SingleOrDefault. SingleOrDefault
will return null
if there is no item (Single
will throw an exception when it can't find the item). Both will throw when there is a duplicate value (two items with the same id
).
var itemToRemove = resultlist.SingleOrDefault(r => r.Id == 2);
if (itemToRemove != null)
resultList.Remove(itemToRemove);
这篇关于如何从C#列表中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!