jwaliszko
jwaliszko

Reputation: 17064

LINQ to SQL into LINQ to Objects - switch via AsEnumerable or via ToList

While there is a necessity of switching from one LINQ driver to another (e.g. because some wanted expressions can be unsupported in the first one) what kind of switch should be used - the AsEnumerable or ToList ?

var r = ent.Users.Select(user => new
        {
            user.Name,
            Organs = user.Attributes.Select(x => x.Organ)
        })
        .AsEnumerable() // switch to LINQ to Objects
        .Select(user => new
        {
            user.Name,
            Organs = string.Join(", ", user.Organs)
        });

I understand that AsEnumerable is deferred, so it doesn't enumerate the source immediately, but is there any significant difference from usage of ToList as the switch here, in practice, instead ?

For LINQ to Objects to run here, the data from SQL should be already available - so it is what ToList() will do if used in the place of the switch. Isn't the usage of AsEnumerable force something like ToList to be invoked internally anyway while evaluation of the expression tree ?

Upvotes: 2

Views: 297

Answers (2)

Diana Ionita
Diana Ionita

Reputation: 3318

While @SLaks already answered your question, for the sake of clarity, I'll quote MSDN on what .AsEnumerable() does:

The AsEnumerable(IEnumerable) method has no effect other than to change the compile-time type of source from a type that implements IEnumerable to IEnumerable itself.

It is not related to ToList().

Upvotes: 0

SLaks
SLaks

Reputation: 887215

.ToList() will build a new List<T> in memory and store all of the objects in it.
That is needless work; you should call .AsEnumerable().

In general, you should only call .ToList() when you need to iterate multiple times (and only at the end of a query chain).

Upvotes: 5

Related Questions