C#中从列表中删除项 [英] c# remove item from list

查看:138
本文介绍了C#中从列表中删除项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有存储在resultlist列表如下:

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?

推荐答案

列表< T> 有两种方法可以使用​​。

List<T> has two methods you can use.

RemoveAt移除(INT指数),如果你知道该项目的索引可以使用。例如:

resultlist.RemoveAt(1);

或者你也可以使用删除(T项目)

var itemToRemove = resultlist.Single(r => r.Id == 2);
resultList.Remove(itemToRemove);

当你不知道该项目确实存在,你可以使用的SingleOrDefault 的SingleOrDefault 将返回如果没有项目(将抛出一个异常时,它无法找到该项目)。当有一个重复的值两者就会抛出(两个项目具有相同 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆