假设:
List<Name> names = new List<Name>(); //list full of names
public void RemoveName(string name) {
List<Name> n = names.Where(x => x.UserName == name);;
names.Remove(n);
}
执行删除的Lambda语法是什么?
如果函数确实删除了,我怎么能得到“成功”的指示?
答案 0 :(得分:31)
names.RemoveAll(x => x.UserName == name);
请注意,所有 lambda语法都提供Predicate<T>
; lambda语法与使用lambda做的内容完全无关。
或者单场比赛(见评论):
var found = names.Find(x => x.UserName == name);
if(found != null) names.Remove(found);
或:
var index = names.FindIndex(x => x.UserName == name);
if(index >= 0) names.RemoveAt(index);
答案 1 :(得分:2)
var n = names.SingleOrDefault(x => x.UserName == name)
if(n != null && n.UserName.length > 0)
{
names.Remove(n);
}
OR
var n= names.Where(x => x.UserName == name).First();
names.Remove(n)