简体   繁体   English

Lambda表达式和方法调用

[英]Lambda Expressions and Method calls

Hi I have a collection of Objects in a Listview and i need to know if i can iterate through them with a lambda expression. 嗨我在Listview中有一个对象的集合,我需要知道我是否可以使用lambda表达式迭代它们。 and call a method on it in the expression. 并在表达式中调用它的方法。

Lets say i need to save a group of people to a database. 让我们说我需要将一群人保存到数据库中。

List<People> someList;
someList.Select(person => person.Save());

is this possible to do? 这可能吗? so far i have not been able to get it working. 到目前为止,我还没有能够使它工作。 thanks 谢谢

You can use the ForEach method of a generic list: 您可以使用通用列表的ForEach方法:

List<People> someList;
someList.ForEach(person => person.Save());
someList.ForEach(p => p.Save());

Sounds like you want a foreach statement: 听起来你想要一个foreach声明:

foreach(People p in someList)
{
    p.Save();
}

But if you really want to do it in lambda expressions and LINQ, then your problem with the above code is that .Select(...) returns an IEnumerable/IQueryable, which creates a new query but doesn't execute your lambda expressions. 但是如果你真的想在lambda表达式和LINQ中这样做,那么上面代码的问题是.Select(...)返回一个IEnumerable / IQueryable,它创建一个新的查询但不执行你的lambda表达式。

You could force the lambda to evaluate by calling an extension method that forces an enumeration of the data the IEnumerable/IQueryable represents. 你可能会迫使拉姆达通过调用迫使了IEnumerable / IQueryable的表示数据的枚举扩展方法来评估。 For instance by doing: 例如通过这样做:

someList.Select(person => person.Save()).Count();

but this also assumes your Save() method returns non-void. 但这也假设您的Save()方法返回非void。

Edit: As others have pointed out, if you're working specifically with a List<>, then you can also do: 编辑:正如其他人所指出的,如果你专门使用List <>,那么你也可以这样做:

someList.ForEach(person => person.Save());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM