Foreach of C# vs Foreach() of EF6

Asked

Viewed 1,167 times

9

Follows code:

ForEach() of EF6:

var result = ctx.Table.Where(x => x.User == "João").ToList();
result.ForEach(x => x.Read = true);
ctx.SaveChanges();

foreach of the C#:

var result = ctx.Table.Where(x => x.User == "João").ToList();
foreach (var item in result)
{
    item.Read = true;
}
ctx.SaveChanges();

I believe the codes above are the same functionality, what is the difference between them?

  • 1

    The RU is Linq, the bottom is not

  • More and the performance ?

2 answers

15

The method ForEach() has no relation to the Entity Framework.

He’s a class method List, see documentation. Note that he has no relation to LINQ, he is a native of List.

There is no important difference between the two. They are two different ways of doing the same thing. Basically the method uses the for to go through all the elements.

Here is the method code:

public void ForEach(Action<T> action) {
    if( action == null) {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
    }
    Contract.EndContractBlock();

    int version = _version;

    for(int i = 0 ; i < _size; i++) {
        if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) {
            break;
        }
        action(_items[i]);
    }

    if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
        ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}

See more in referencesource.microsfot.com

Obviously it changes the way the code is written/read a lot, which is better or more readable is a matter of taste.

I find it interesting to read this article by Eric Lippert that deals with the subject (not directly from your question, but treats).

  • I’d like to know how this one works ForEach(), you could explain to me?

  • What do you mean, @cat? It’s the same thing from foreach normal. I’m not sure I understand your question.

  • It seems to me a method, as this method manages to interact in a list and to achieve the same result of foreach?

  • He gets a Action<T>, right? Internally it is passed through all items in the list and this action is called for all elements. Something like foreach(T element in this._itens) { action(element) }. Understands?

  • So deep down it’s a foreach!? You could even create your own ForEach() so I thought he was something native to the language.

  • 1

    @Yes, it’s a cat foreach. I thought that was clear in the answer :p (I will edit). He is part of the class List, has nothing to do with the language itself.

  • @cat Actually it’s a for

  • I was thinking, q a for would be more performatic ;P

Show 3 more comments

9


Contrary to what it may seem, the Entity Framework LINQ codes will attempt to generate an SQL expression or something equivalent that processes the database data. It will not execute exactly the code that is written there. This is called DSL (Domain Specific Language). It must occur with the Where() used earlier to acquire what is in the database.

But it should not occur with the ForEach() that does not exist in the EF LINQ provider. So the difference between them is almost syntactic.

To know which takes longer would have to do tests. The problem is that both are abstractions that have cost. The foreach need to take an iterator that is an external object to the collection to control the progress of each item. This is not free. Already the ForEach() of List is a for simple without iterator, which is faster. On the other hand it needs to call a delegate in each iteration, which is not for free.

In general he is used for processing parallelization not possible with the command foreach, It is a little more expensive, but if there are gains (there are not always) may end before running in parallel. In this case it is only a processing in the application upon the result brought by the database.

There are people who like him in any situation by getting shorter and eventually more semantic about what he wants to do. But performance is not good if it doesn’t parallelize well. And parallelization isn’t even available in every implementation of ForEach(). Contrary to what people imagine it is not a unique method, it can have several flavors.

See more:

  • But there is ForEach para Ienumerable?

  • No, it doesn’t make much sense. It is at best a method of convenience. The goal of LINQ is to make queries and not processing. The goal of ForEach() is processing.

  • I think I confused something in the answer. Why would the first code take longer?

  • Try to see these links that explains the functioning of LINQ. It is an abstraction with an extra cost of a state machine to manage each step of the execution, unlike foreach which is a cleaner code (but not so much because in some cases the for can be even faster).

  • Ok. I have a basis of how LINQ works, but there is no LINQ there (except for the query). There is?

  • @LINQ there I got confused. This ForEach is not even LINQ, this is "native" of List as you replied. I will improve the answer because this may not be true. Thank you for having spoken.

  • LINQ has some kind of foreach? If the ForEach() is from List then what would be the foreach of LINQ?

  • There is no cat

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.