【问题标题】:Not able to remove a Generic List object in c#无法在 C# 中删除通用列表对象
【发布时间】:2013-07-17 13:48:04
【问题描述】:
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

请帮忙。

 public class SessionResponseList{

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

【问题讨论】:

标签: c# asp.net


【解决方案1】:

您应该尝试使用 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)

【讨论】:

    猜你喜欢
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 2014-03-15
    • 1970-01-01
    • 2012-11-25
    • 2019-02-12
    • 1970-01-01
    相关资源
    最近更新 更多