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?
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?
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.
Browser other questions tagged c# linq lambda-expressions
You are not signed in. Login or sign up in order to post.
Good alternative. + 1.
– Leonel Sanches da Silva
Sorry, I bother you, but, I wouldn’t use this method, because, you (@Ciganomorrisonmendez and Ommi) know which SQL it will generate?
– user6026
@Harrypotter I never tested. Which?
– Leonel Sanches da Silva
With his answer he generates a
in(1,2,3,4)
withAny
it uses Exits and writes a Sql Unioll All to for each item onWHERE 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!– user6026
VEESH! Messed up, huh? Good, but if it’s for a few I think it’s okay.
– Leonel Sanches da Silva
@Ciganomorrisonmendez, is only a tip after I’ve been erasing such information, do not want to create bad being !!! thanks!
– user6026
Nah, never mind. It’ll be useful to someone.
– Leonel Sanches da Silva
@Harrypotter interesting fact. Any alternative? I usually try to avoid Ins, but an alternative was interesting to know.
– Omni
@Omni, I use it like this,
in
when it is a fixed datum, andexits
when I need to scan another SQL, but in both cases theSQL
is a line, and in this case proposed byAny
a great SQL is generated and I believe that there the performance ofEntity
gets bad. I asked once to a DBA SQL Server and Oracle they say that today both thein
as to theexits
has similar performance, but, the problem that in thisAny
it generated a great SQL look at the link: http://codepad.org/jREAd5EM, type was an array from 1 to 10.– user6026
@Ciganomorrisonmendez has a look at the result: http://codepad.org/jREAd5EM
– user6026