[英]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. 与其创建一个新实例, FirrstOrDefault
尝试使用FirrstOrDefault
从列表中获取该实例,如果找到该实例,则将该实例从列表中删除,当前您正在创建一个新对象,并试图将其从列表中删除。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.