Error using Split inside Select

Asked

Viewed 58 times

4

Why the exception below occurs when using Split within a Select in a IQueryable?

The LINQ Expression Node type 'Arrayindex' is not supported in LINQ to Entities.

I already managed to solve the problem using ToList and doing the Select with Split in it, but I would like to understand what is the reason for the problem.

Thus occurs exception:

var retorno = entities.tabela.Where(x => x.coluna1 == null)
    .Select(x => new { Campo1 = x.coluna1, Campo2 = x.coluna2 });

retorno = retorno.Select(x => new { x.Campo1, Campo2 = x.Campo2.Split(' ')[0] });

That’s how it works:

var retorno = entities.tabela.Where(x => x.coluna1 == null)
    .Select(x => new { Campo1 = x.coluna1, Campo2 = x.coluna2 }).ToList();

retorno = retorno.Select(x => new { x.Campo1, Campo2 = x.Campo2.Split(' ')[0] }).ToList();

1 answer

2


I already managed to solve the problem using ToList and doing the Select with Split in it, but I would like to understand what is the reason for the problem.

The reason begins in this explanation. Without solving the enumeration, your IQueryable tries to pass the Split for an SQL equivalent, which does not exist.

It must be understood that DbSet implements so much IQueryable how much IEnumerable. By calling ToList(), you ask LINQ to solve the enumeration, and so it runs SQL. Like Split in the second example was for the collection already solved, the Select acts on the collection in memory, and no more generation of SQL.

  • 2

    How cool! I thought the darlings were executed whenever I wore Select or Where. This explains another problem I had when I tried to join IQueryable and List.

  • @Danieldutra You see more details, in the answer here (which is also from Gypsy)

  • @jbueno the Gypsy already linkou she in response, vlw!

  • Ouch. I had not seen, thanks for warning.

  • Just confirm me something that I don’t think is worth a new question: ask a foreach in new List<string>().Select(...) and new List<string>().Select(...).ToList() is the same, right? In this case the Select is actually executed when I "call him", right?

  • 2

    Ops, in fact, is rather the same thing. Had not attempted that the example used a list. If you do the Select in a list, yes it’s pretty much the same thing. The only difference is that without the ToList() iteration will be done in a IEnumerable, with the ToList() it is made in a list. By the way, I think it is worth a question.

  • http://answall.com/questions/129779/foreach-em-select-e-list !

Show 2 more comments

Browser other questions tagged

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