您需要将代码更改为以下内容:
if (String.IsNullOrEmpty(comenttext)) //incase user clears the textbox
{
for (var i = 0; i < commentlist.Count; i++)
{
if (commentlist[i].id == (int)commentid)
{
var itemToRemove = commentlist.Single(r => r.id == (int)commentid);
commentlist.Remove(itemToRemove);
break;
}
}
}
else
{
bool found = false;
for (var i = 0; i < commentlist.Count; i++)
{
if ((commentlist[i].id) == ((int)commentid))
{
commentlist[i].comment = comenttext;
found = true;
break;
}
}
if (! found)
commentlist.Add(new CommentModel((int)commentid, (string)comenttext));
}
类似地,您可以在if子句中找到条目后退出循环,但在这种情况下,您只会浪费时间,因为您已经删除了id的条目
没有for循环的较短LINQ解决方案可以是:
var itemInList = commentlist.Where(li => li.id == (int)commentid).FirstOrDefault();
if (String.IsNullOrEmpty(comenttext)) //incase user clears the textbox
{
if (itemInList != null)
commentlist.Remove(itemInList);
}
else //add new or update incase its a comment change
{
if (itemInList != null)
itemInList.comment = comenttext;
else
commentlist.Add(new CommentModel((int)commentid, comenttext));
}