通过 LINQ 将函数应用于集合的所有元素 [英] Apply function to all elements of collection through LINQ
问题描述
我最近开始使用 LINQ,它很棒.我想知道 LINQ 是否允许我在不使用 foreach 的情况下将函数(任何函数)应用于集合的所有元素.类似于 python lambda 函数的东西.
I have recently started off with LINQ and its amazing. I was wondering if LINQ would allow me to apply a function - any function - to all the elements of a collection, without using foreach. Something like python lambda functions.
例如,如果我有一个 int 列表,我可以使用 LINQ 为每个元素添加一个常量吗
For example if I have a int list, Can I add a constant to every element using LINQ
如果我有一个数据库表,是否可以使用 LINQ 为所有记录设置一个字段.
If i have a DB table, can i set a field for all records using LINQ.
我正在使用 C#
推荐答案
解决这个问题的常用方法是在 IEnumerable
上添加您自己的 ForEach
泛型方法.这是我们在 MoreLINQ 中得到的:
A common way to approach this is to add your own ForEach
generic method on IEnumerable<T>
. Here's the one we've got in MoreLINQ:
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
source.ThrowIfNull("source");
action.ThrowIfNull("action");
foreach (T element in source)
{
action(element);
}
}
(其中 ThrowIfNull
是任何引用类型的扩展方法,它的作用显而易见.)
(Where ThrowIfNull
is an extension method on any reference type, which does the obvious thing.)
看看这是否是 .NET 4.0 的一部分会很有趣.它违背了 LINQ 的函数式风格,但毫无疑问,很多人都觉得它很有用.
It'll be interesting to see if this is part of .NET 4.0. It goes against the functional style of LINQ, but there's no doubt that a lot of people find it useful.
一旦你有了它,你可以写这样的东西:
Once you've got that, you can write things like:
people.Where(person => person.Age < 21)
.ForEach(person => person.EjectFromBar());
这篇关于通过 LINQ 将函数应用于集合的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!