Sending items in a LINQ sequence to a method that returns void

▼魔方 西西 提交于 2019-12-04 23:47:53

First of all, your current code will not work.
Select, and most other LINQ methods, use deferred execution, meaning that they don't actually do anything until you enumerate the results.

In general, you should never use a lambda with side effects in a LINQ query.

To answer your question, you should use a foreach loop.

You're looking for a ForEach extension method; Eric Lippert explains why Microsoft didn't write one.

If you really want to, you can write one yourself:

public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action) {
    if (sequence == null) throw new ArgumentNullException("sequence");
    if (action == null) throw new ArgumentNullException("action");
    foreach(T item in sequence) 
        action(item);
}

//Return false to stop the loop
public static void ForEach<T>(this IEnumerable<T> sequence, Func<T, bool> action) {
    if (sequence == null) throw new ArgumentNullException("sequence");
    if (action == null) throw new ArgumentNullException("action");

    foreach(T item in sequence) 
        if (!action(item))
            return;
}

The common consensus is that LINQ is for querying and selection... while you use traditional iterative methods for looping and iteration.

I hate to say this but you would use a traditional foreach loop because you want your linq queries to execute, and you iterate over the resulting IEnumerable. It helps with code readability, and I will admit LINQ is addictive. You want to do everything using Lambdas and deferred execution, but looping should be left to your traditional C# looping methods. This will definitely help with side-effects.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!