根据条件从列表中删除项目 [英] Remove item from list based on condition

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

问题描述

public struct stuff
{
    public int ID;
    public int quan;
}

我要删除ID 的产品 =1。我目前正在尝试这样做:

I want to to remove a product where ID = 1. I'm trying this currently:

prods.Remove(new stuff{ prodID = 1});

,它不起作用。

感谢所有人

推荐答案

使用linq:

prods.Remove( prods.Single( s => s.ID == 1 ) );

也许您甚至想使用 SingleOrDefault(),然后检查元素是否根本存在...

Maybe you even want to use SingleOrDefault() and check if the element exists at all ...

编辑:

stuff 是一个结构, SingleOrDefault()不会返回null。但是它将返回 default(stuff),其ID为0。当您的 normal 填充对象的ID为0时,您可以查询对于此ID:


Since stuff is a struct, SingleOrDefault() will not return null. But it will return default( stuff ), which will have an ID of 0. When you don't have an ID of 0 for your normal stuff-objects you can query for this ID:

var stuffToRemove = prods.SingleOrDefault( s => s.ID == 1 )
if( stuffToRemove.ID != 0 )
{
    prods.Remove( stuffToRemove );
}

这篇关于根据条件从列表中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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