C# 如何使用 Lambda 语法从列表中删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14358372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to remove from list using Lambda syntax
提问by darko
Given:
鉴于:
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);
}
What's the Lambda syntax to execute the removal?
执行删除的 Lambda 语法是什么?
And how can I get indication of "success" if the function did remove or not?
如果该功能确实删除了,我如何才能获得“成功”的指示?
采纳答案by Marc Gravell
names.RemoveAll(x => x.UserName == name);
Note here that all the lambda syntaxdoes is provide a Predicate<T>
; lambda syntax is entirely unrelated to what it ends up doingwith the lambda.
请注意,所有lambda 语法所做的都是提供一个Predicate<T>
; lambda 语法与它最终用 lambda做的事情完全无关。
Or for a single match (see comments):
或单场比赛(见评论):
var found = names.Find(x => x.UserName == name);
if(found != null) names.Remove(found);
or:
或者:
var index = names.FindIndex(x => x.UserName == name);
if(index >= 0) names.RemoveAt(index);
回答by andy
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)