使用 iList 处理失败的项目
如果能有处理列表中每个项目的速记(在本例中是保存的),那就太好了。
所以
var people = MakePeople();
foreach (var person in people)
{
session.Save(person);
}
我们可以使用
var cards = MakeCards(deck);
cards.Select(session.Save);
但是,那不起作用..建议?总计的?
It would be great to have shorthand for processing every item in a list, in this case saving.
SO intead of
var people = MakePeople();
foreach (var person in people)
{
session.Save(person);
}
we could use
var cards = MakeCards(deck);
cards.Select(session.Save);
But, that doesn't work.. Suggestions? Aggregate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Select
使用惰性求值,因此不起作用。您正在寻找
List.ForEach
或其 不存在的 LINQ 版本。Select
uses lazy evaluation, so it won't work.You're looking for
List<T>.ForEach
, or its non-existent LINQ version.看起来
Save()
没有返回值。要与Select()
一起使用该方法,它需要有一个返回值。一般来说,将 LINQ 与具有副作用的方法(例如
Save()
)一起使用并不是一个好主意。当有副作用时,当然首选第一种方法。如果 MakePeople 返回一个具体的列表,您也可以尝试:It looks like
Save()
has no return value. To use the method withSelect()
, it needs to have a return value.In general, it's a bad idea to use LINQ with methods that have side effects (like
Save()
). When there are side-effects, the first method is certainly preferred. If MakePeople returns a concrete List, you could also try:列表有一个
ForEach(Actionaction)
方法。List has a
ForEach(Action<T> action)
method.您尝试创建卡片 ->虚空映射。选择旨在将一个项目转换为另一种类型,以便您可以将卡片集合转换为卡号集合等。
正如其他人已经提到的,List 有一个 ForEach 重载。但 C# 语言设计者的一般主题(请参阅 Eric Lipperts 博客)是不提供这样的扩展方法,因为 foreach 更清晰。它并不能保证你大量的打字,所以这里的好处是微乎其微的。
作为参考,您可以创建一个扩展方法,这样只需 3 行代码即可完成您想要的操作。
Nitpick Corner:我的意思是并且写道(至少一位有影响力的)C# 语言设计者不想引入这种扩展方法。一旦它存在于 BCL 中,任何 .NET 语言都可以使用它。
你的,
阿洛伊斯·克劳斯
You tried to create a Card -> Void mapping. Select is meant to convert one item to another type so you can convert a card collection to e.g. a cardnumber collection.
As the others have already mentioned List has a ForEach overload. But the general theme of the C# language designers (see Eric Lipperts blog) was to not provide such an extension method since foreach is clearer. It does not safe you an awful amount of typing so the benefit here is minmal.
For refernce you can create an extension method like that does what you want with 3 lines of code.
Nitpick Corner: I did mean and write that (at least one influental) C# language designer did not want to introduce this extension method. Once it exists in the BCL it can be used by any .NET language.
Yours,
Alois Kraus