What is the fastest way to set properties (any one) to null
in an IEnumerable
? Is foreach
my only option?

- 6,570
- 9
- 45
- 63

- 3,061
- 11
- 43
- 61
-
1All properties of all objects in an `IEnumerable
` or one property of all objects in an `IEnumerable – Tim Schmelter Jan 28 '13 at 15:24`? -
`foreach` is the most natural option. Why on earth would you consider such a natural and simple solution and then go looking for something else? – Jon Jan 28 '13 at 15:25
-
2define 'fastest'. the code that will run the fastest, or the fastest way for you as a programmer to do it? – Mike Corcoran Jan 28 '13 at 15:26
-
1@MikeCorcoran the first, of course – chtenb Jan 28 '13 at 15:29
2 Answers
If you have a very large list, you could consider doing this in parallel:
enumerable.AsParallel().ForAll(a => a.Value = null);
But worth benchmarking and baring in mind that your objects will now need to be threadsafe.
Quick tests here showed a return on investment when the list size was above 10 million items*. Lower list sizes and the costs of setting up the parallel processing outweighs the benefits.
*Your Mileage Will Vary

- 54,145
- 21
- 145
- 203
-
1Of course the empirical 10 million limit may depend very much on the hardware architecture used (and on what else is going on on that machine). – Jeppe Stig Nielsen Jan 28 '13 at 16:02
There are two ways of achieving your goal:
As you mentioned:
foreach(var item in enumeration) { item.Property = null; }
You can go with LINQ also:
enumeration.ToList().ForEach(item => item.Property = null);
While the second way looks a shorter and better readable, it may execute slower, because as Jeppe Stig Nielsen pointed out, the IEnumerable
gets converted into a List
(be enumerating it the first time) and that list gets enumerated again, to finally set the property.
Thus you are right: foreach
is your only option. However the foreach
-representation will look like, you always will need to iterate over the collection to modify each item.

- 6,570
- 9
- 45
- 63
-
3Your option 2 is uglier and slower. It first creates a new `List<>` object and iterates through `enumeration` (the LINQ extension). Then it iteratates through the new `List<>` object (the `ForEach` instance method on `List<>`). So two iterations instead of one, a lot of values (references) are copied in the first iteration, so more memory is used. The `List<>` instance is not kept and will be garbage collected. – Jeppe Stig Nielsen Jan 28 '13 at 15:35
-
@JeppeStigNielsen thanks for pointing that out. I adopted my answer accordingly. – Spontifixus Jan 28 '13 at 15:46