Say I have a class:
public class MyClass
{
...
}
and a webservice method that returns an IEnumerable<MyClass>
The consumer of the webservice defines some method:
public void DoSomething(MyClass myClass)
{
...
}
Now, the consumer can call DoSomething
on the result of the webservice method in two ways:
var result = // web service call
foreach(var myClass in result)
{
DoSomething(myClass);
}
or:
var result = // web service call
result.ToList().ForEach(DoSomething);
Needless to say I much prefer the second way since it is much shorter and more expressive (once you get used to the syntax, which I have).
Now, the web service method only exposes an IEnumerable<MyClass>
, but it actually returns a List<MyClass>
which (AFAIK) means that the actual serialized object is still a List<T>
. However, I have found (using reflector) that the Linq method ToList()
makes a copy of all the objects in the IEnumerable<T>
regardless of the actual runtime type (in my opinion, it could just have casted the argument to a List<T>
if it already was one).
This obviously has some performance overhead, especially for large list (or lists of large objects).
So what can I do to overcome this problem, and why is there no ForEach
method in Linq?
By the way, his question is vaguely related to this one.