call a function for each value in a generic c# collection

Viewed 111241

I have a collection of integer values in a List collection. I want to call a function for each value in the collection where one of the function's argument is a collection value. Without doing this in a foreach loop... is there a way to accomplish this with a lambda/linq expression?

something like... myList.Where(p => myFunc(p.Value)); ?

thanks in advance, -s

8 Answers

LINQ doesn't help here, but you can use List<T>.ForEach:

List<T>.ForEach Method

Performs the specified action on each element of the List.

Example:

myList.ForEach(p => myFunc(p));

The value passed to the lambda expression is the list item, so in this example p is a long if myList is a List<long>.

As other posters have noted, you can use List<T>.ForEach.

However, you can easily write an extension method that allows you to use ForEach on any IEnumerable<T>

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    foreach(T item in source)
        action(item);
}

Which means you can now do:

myList.Where( ... ).ForEach( ... );

You could use the List.ForEach method, as such:

myList.ForEach(p => myFunc(p));

No - if you want to call a function for each item in a list, you have to call the function for each item in the list.

However, you can use the IList<T>.ForEach() method as a bit of syntactic sugar to make the "business end" of the code more readable, like so:

items.ForEach(item => DoSomething(item));

If you don't wan't to use the ForEach method of List<T>, but rather use IEnumerable<T> (as one often does when "LINQ:ing"), I suggest MoreLINQ written by Jon Skeet, et al.

MoreLINQ will give you ForEach, and also Pipe (and a bunch of other methods), which performs an action on each element, but returns the same IEnumerable<T> (compared to void).

Related