Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subquery in a Lambda Expression or LINQ

Tags:

c#

lambda

linq

How can you write this query using a lambda expression or LINQ:

SELECT    *
FROM      vehicles 
WHERE     (memo1 like '%CERTIFIED%' OR memo2 = 'CERTIFIED')
AND       stockno IN (SELECT stockno FROM udealer2 where ACC='UCERT')
ORDER BY  model, days DESC
like image 706
obautista Avatar asked Nov 20 '11 02:11

obautista


People also ask

Can you use Lambda expression instead of LINQ query?

So performance-wise, there's no difference whatsoever between the two. Which one you should use is mostly personal preference, many people prefer lambda expressions because they're shorter and more concise, but personally I prefer the query syntax having worked extensively with SQL.

Which is faster LINQ or lambda?

There is no performance difference between LINQ queries and Lambda expressions.

Which is better lambda or LINQ?

Adding with Kristin's answer, There is no difference in performance because after compile they generate same IL code for the same query. Language Integrated Query (LINQ) is feature of Visual Studio that gives you the capabilities yo query on the language syntax of C#, so you will get SQL kind of queries.

Under which clause should the subquery be?

A subquery is usually added within the WHERE Clause of another SQL SELECT statement. You can use the comparison operators, such as >, <, or =. The comparison operator can also be a multiple-row operator, such as IN, ANY, or ALL.


1 Answers

Not knowing much about your model, here is a blind mechanical translation of your query:

vehicles.Where( v =>
    (SqlMethods.Like(v.memo1, "%CERTIFIED%") || v.memo2 == "CERTIFIED") &&
    udealer2.Any(d => d.ACC == "UCERT" && d.stockno == v.stockno)
).OrderBy(v => v.model)
.ThenByDescending(v => v.days)
like image 182
Sergey Kalinichenko Avatar answered Oct 06 '22 00:10

Sergey Kalinichenko