Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do an IN or CONTAINS in LINQ using LAMBDA expressions?

I have the following Transact-Sql that I am trying to convert to LINQ ... and struggling.

SELECT * FROM Project
WHERE Project.ProjectId IN (SELECT ProjectId FROM ProjectMember Where MemberId = 'a45bd16d-9be0-421b-b5bf-143d334c8155')

Any help would be greatly appreciated ... I would like to do it with Lambda expressions, if possible.

Thanks in advance!

like image 651
mattruma Avatar asked Dec 09 '08 05:12

mattruma


People also ask

How add contains in LINQ?

LINQ Contains will not be supported in Query syntax it will be available only in the method syntax. Let's see the following syntax for LINQ-Contains, the Contains extension method available in two overloaded methods, public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value);

How do you use LINQ to check if a list of strings contains any string in a list?

Select(x => new { x, count = x. tags. Count(tag => list. Contains(tag)) }) .

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.

What is lambda expression in LINQ?

The term 'Lambda expression' has derived its name from 'lambda' calculus which in turn is a mathematical notation applied for defining functions. Lambda expressions as a LINQ equation's executable part translate logic in a way at run time so it can pass on to the data source conveniently.


1 Answers

GFrizzle beat me to it. But here is a C# version

var projectsMemberWorkedOn = from p in Projects
                    join projectMember in ProjectMembers on
                        p.ProjectId equals projectMember.ProjectId
                    where projectMember.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155"
                    select p;

And as a bonus a purely LINQ method chain version as well:

var projectsMemberWorkedOn =
            Projects.Join( ProjectMembers, p => p.ProjectId, projectMember => projectMember.ProjectId,
                ( p, projectMember ) => new { p, projectMember } )
                .Where( @t => @t.projectMember.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155" )
                .Select(@t => @t.p );
like image 126
Strelok Avatar answered Nov 15 '22 05:11

Strelok