Jesper Niedermann's .NET Blog
about .NET and related technologies RSS 2.0
# Friday, 01 May 2009

If you want to Execute something on each element of the result of a Linq expression. You can either loop over the result using foreach(...) or turn the result into a List using .ToList(), and then use .Foreach(...) on the resulting list. Like this:

(from excep in ErrorList
where excep is ArgumentException select excep)
.ToList().ForEach(e => Console.WriteLine(e.Message));

This is ugly, and I prefer to make my own Extension method for IEnumerable<T> called Execute(...):

public static void Execute<T>(this IEnumerable<T> list, Action<T> action)
{
foreach(T element in list)
{
action(element);
}
}

This means you can do this instead:

(from excep in ErrorList
where excep is ArgumentException select excep)
.Execute(e => Console.WriteLine(e.Message));

Back in the days when I used Linq in a program for the first time, I wondered why there was no way to execute an action on each element of a list, so I implemented the Execute method.

It was only later that I discovered that the default way was .ToList().Foreach(...)

I must say I still prefer my original approach.

BTW: In a small none scientific test I have tested the two approaches.

With Linq To Objects iterating over 100000 integers and printing them to the Console takes about 21 seconds with the Foreach method and about 20 seconds with the Execute method, so it is even faster at least for this particular example. Though nothing to get excited about. :O)

The test was done in a Vista VPC with VS2008,

Small performance test: LinqPerfTest.zip

Friday, 01 May 2009 21:12:40 (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET | Linq | Tips & Tricks
Comments are closed.
Archive
<2017 December>
SunMonTueWedThuFriSat
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456
About the author/Disclaimer
I am a software architect with focus on Microsoft Technologies. I have been working with these in different large companies since 1995. I am currently employed at UVdata A/S.
Here is my View Jesper Niedermann's profile on LinkedIn

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Privacy policy
The privacy policy of this site.

© Copyright 2017
Jesper Niedermann
Sign In
Statistics
Total Posts: 28
This Year: 0
This Month: 0
This Week: 0
Comments: 32
All Content © 2017, Jesper Niedermann
DasBlog theme 'Niedermann' created by Jesper Niedermann, based on 'Business' created by Christoph De Baene (delarou)