Clause in with lambda

Asked

Viewed 1,552 times

4

Is it possible to have an IN clause with lambda Expression? Type:

context.tabela.Where(a => a.meu_campo_id_tipo_inteiro....)

let’s say one in like this: (2,3,4,5) As I put it in the dots?

2 answers

7


More or less. The way to do it is like this:

var inteirosPraAchar = new List<int> {2, 3, 4, 5};
context.tabela.Where(a => inteirosPraAchar.Contains(a.meu_campo_id_tipo_inteiro));

4

An alternative to the method in the @Gypsy:

List<int> inteirosParaAchar = new List<int> { 1, 2, 3, 4 };
context.Where(i => inteirosParaAchar.Any(i1 => i1 == i));

For the reasons stated in this reply (concerning flexibility), the use of Any makes the comparison more flexible and can be extended to include more comparison elements.

Excerpt from the answer:

Finally, the . Any() due to the delegate, is more flexible than . Contains() which only accepts an object.

  • 2

    Good alternative. + 1.

  • Sorry, I bother you, but, I wouldn’t use this method, because, you (@Ciganomorrisonmendez and Ommi) know which SQL it will generate?

  • @Harrypotter I never tested. Which?

  • 1

    With his answer he generates a in(1,2,3,4) with Any it uses Exits and writes a Sql Unioll All to for each item on WHERE EXISTS (SELECT 1 AS [C1] FROM (SELECT [UnionAll8].[C1] AS [C1] FROM (SELECT [UnionAll7].[C1] AS [C1] FROM (SELECT [UnionAll6].[C1] AS [C1] if you have 100 items it generates an unnecessary big SQL in my view!. If you merge SQL In with Exits, the encoding is different from this one! And look I’m very concerned with what coding generates!

  • VEESH! Messed up, huh? Good, but if it’s for a few I think it’s okay.

  • @Ciganomorrisonmendez, is only a tip after I’ve been erasing such information, do not want to create bad being !!! thanks!

  • Nah, never mind. It’ll be useful to someone.

  • @Harrypotter interesting fact. Any alternative? I usually try to avoid Ins, but an alternative was interesting to know.

  • 1

    @Omni, I use it like this, in when it is a fixed datum, and exits when I need to scan another SQL, but in both cases the SQL is a line, and in this case proposed by Any a great SQL is generated and I believe that there the performance of Entity gets bad. I asked once to a DBA SQL Server and Oracle they say that today both the in as to the exits has similar performance, but, the problem that in this Any it generated a great SQL look at the link: http://codepad.org/jREAd5EM, type was an array from 1 to 10.

  • 1

    @Ciganomorrisonmendez has a look at the result: http://codepad.org/jREAd5EM

Show 5 more comments

Browser other questions tagged

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