为每个项目中的字段分配值的扩展方法?
我可以发誓已经为 Queryable 类构建了一个扩展方法,但我只是找不到,但也许我正在考虑一些不同的东西。
我正在寻找类似的内容:
IQueryable<Entity> en = from e in IDB.Entities select e;
en.ForEach(foo => foo.Status = "Complete");
en.Foreach() 必须执行:
foreach(Entity foo in en){
foo.Status = "Complete";
}
这已经写了吗? 如果没有,是否可以编写所述扩展方法,最好允许任何 LINQ 表和该表上的任何字段。 从哪里开始比较好?
I could have sworn that there was an extension method already built for the Queryable class that I just can't find, but maybe I'm thinking of something different.
I'm looking for something along the lines of:
IQueryable<Entity> en = from e in IDB.Entities select e;
en.ForEach(foo => foo.Status = "Complete");
en.Foreach() would essential perform:
foreach(Entity foo in en){
foo.Status = "Complete";
}
Is this already written? If not, is it possible to write said Extension Method, preferably allowing for any LINQ Table and any Field on that table. Where is a good place to start?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基类库中没有任何内容。 然而,许多许多开发人员在他们自己的公共库中都有这个,我们在 MoreLINQ 也是如此。
它有点违背 LINQ 的精神,因为它都是关于副作用的 - 但它确实有用,所以我认为实用主义在这里胜过教条。
需要注意的一件事 - 在您的示例中使用查询表达式确实没有意义。 (这并不是完全多余,但如果您不公开该值,那也没关系。)选择在这里没有做任何有用的事情。 你可以这样做:
即使你想做一个“where”或“select”,我通常会使用点表示法:
仅使用查询表达式,它们实际上使代码更简单:)
There's nothing in the base class library. Many, many developers have this in their own common library, however, and we have it in MoreLINQ too.
It sort of goes against the spirit of LINQ, in that it's all about side-effects - but it's really useful, so I think pragmatism trumps dogma here.
One thing to note - there's really no point in using a query expression in your example. (It's not entirely redundant, but if you're not exposing the value it doesn't matter.) The select isn't doing anything useful here. You can just do:
Even if you want to do a single "where" or "select" I'd normally use dot notation:
Only use query expressions where they actually make the code simpler :)
List<> 上有一个 foreach。 大致是这样的:
There is a foreach on a List<>. Roughly something along these lines: