简体   繁体   English

如何从 Ilist 中删除项目

[英]How to remove items from Ilist

I have an IList , I also have a method which checks if the item is already in list and if it is I need it to be deleted/ removed and add again.我有一个 IList ,我还有一个方法可以检查该项目是否已经在列表中,如果是,我需要将其删除/删除并再次添加。

 private PurchaseItemViewModel CheckSessionPurchaseItemViewModel(long purchaseLevelId)
        {
            bool itemFound = false;
            PurchaseItemViewModel purItem = new  PurchaseItemViewModel();

            foreach (var item in UserSession.UserDataPurchaseItems)
            {
                if (item.PurchaseLevelId == purchaseLevelId)
                {
                    itemFound = true;
                    purItem.Note = item.Note;
                    purItem.PurchaseAmount = item.PurchaseAmount;
                    purItem.PurchaseLevelId = item.PurchaseLevelId;
                }
            }

            if (itemFound)
            {
                return purItem;
            }

            return null;
    }

If it the above method finds the purchase item then it returns an object else null.如果上面的方法找到了购买的项目,那么它返回一个对象,否则为 null。

IList<PurchaseItemViewModel> purchaseSessionList = UserSession.UserDataPurchaseItems;
PurchaseItemViewModel pItem = CheckSessionPurchaseItemViewModel(levelId);
if(pItem != null)
{
    purchaseSessionList.Remove(item);
}

So the issue is with the below line it is not removing the item , it does not even error.所以问题在于下面一行它没有删除项目,它甚至没有错误。

**purchaseSessionList.Remove(item);**

Use this code for removing:使用此代码删除:

if(pItem != null) purchaseSessionList.Remove( purchaseSessionList.SingleOrDefault( s => s.PurchaseLevelId== levelId) );

IMHO you don't need to create pItem, would be enough to return false or true or item primary key.恕我直言,您不需要创建 pItem,足以返回 false 或 true 或 item 主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM