应用功能集合,通过LINQ的所有元素 [英] Apply function to all elements of collection through LINQ

查看:205
本文介绍了应用功能集合,通过LINQ的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始了与LINQ和其惊人的。我在想,如果LINQ可以让我一个功能应用 - 任何功能 - 一个集合中的所有元素,而无需使用的foreach。像蟒蛇波长的职能。

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#

推荐答案

接近一个常见的​​方法是在的ForEach 泛型方法>的IEnumerable< T> 。下面是我们已经有了在一个 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屋!

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