简体   繁体   中英

Not able to remove a Generic List object in c#

SessionResponseList objClientSessionResponseList = new SessionResponseList();
objClientSessionResponseList.QId = Convert.ToInt32(Session["QuestionNumber"]);
objClientSessionResponseList.QAnswer = Session["CurrentAnswer"].ToString();
objSessionResponseList = (List<SessionResponseList>)Session["Answers"];
if (objSessionResponseList.Where(x=>x.QId == objClientSessionResponseList.QId && x.QAnswer==objClientSessionResponseList.QAnswer).Count()>0)
{
    objSessionResponseList.Remove(objClientSessionResponseList);
    Session["Answers"] = objSessionResponseList;

}
//  objSessionResponseList.Remove(objClientSessionResponseList); 
//This isn't working tried everything the values are exact duplicate

Please help.

 public class SessionResponseList{

    public int QId { get; set; }
    public string QAnswer { get; set; }
}

Instead of creating a new instance you should try getting the instance from the List using FirrstOrDefault and if that is found then remove that instance from the list, currently you are creating a new object and you are trying to remove that from the list.

var itemToBeRemoved = objSessionResponseList
                    .FirstOrDefault(x=> 
                    x.QId == Convert.ToInt32(Session["QuestionNumber"]) &&
                    x.QAnswer == Session["CurrentAnswer"].ToString();

if(itemToBeRemoved != null) //means item is found in the list
    objSessionResponseList.Remove(itemToBeRemoved)

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