views:

323

answers:

6

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

+1  A: 

You can use the ForEach method:

MSDN:

http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx

tster
+4  A: 

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>.

dtb
thanks- this is exactly what i was looking for and probably saw somewhere but couldn't remember...
Stratton
+2  A: 

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

myList.ForEach(p => myFunc(p));
Matt Hamsmith
+2  A: 

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));
Neil Barnwell
+1  A: 

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).

Martin R-L
A: 

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( ... );
Winston Smith