如何使用Lambda语法从列表中删除 [英] how to remove from list using Lambda syntax

查看:269
本文介绍了如何使用Lambda语法从列表中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出:

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语法是什么?

What's the Lambda syntax to execute the removal?

如果该函数确实删除了,我如何获得成功"的指示?

And how can I get indication of "success" if the function did remove or not?

推荐答案

names.RemoveAll(x => x.UserName == name);

请注意,所有 lambda语法所做的只是提供一个Predicate<T>; lambda语法与用lambda做的结果完全无关.

Note here that all the lambda syntax does is provide a Predicate<T>; lambda syntax is entirely unrelated to what it ends up doing with the lambda.

或进行一场比赛(查看评论):

Or for a single match (see comments):

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);

这篇关于如何使用Lambda语法从列表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆