简体   繁体   中英

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.

 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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