471,596 Members | 803 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,596 software developers and data experts.

linq query help

Hello,

I need some assistance with a LINQ query. I've got a simple query:

var q = from t in db.Table1 select t;

Based on user input I'm adding some where clauses:

if (condition1)
q = q.Where(t =t.Field1==1);
if (condition2)
q = q.Where(t =t.Field2==2);

Table1 has a sub table. Based on a condition I want find the Table1 records
that have one or more Table2 records. If I were using sql I would do
something like this:

select * from Table1 t1 where exists (select * from Table2 t2 where
t1.id=t2.id and t2.field1='somevalue')

How can I do this in LINQ given that I have added the above where clauses
based on those conditions?

Thanks,
Nick
Jul 23 '08 #1
2 1299
Nick wrote:
Hello,

I need some assistance with a LINQ query. I've got a simple query:

var q = from t in db.Table1 select t;

Based on user input I'm adding some where clauses:

if (condition1)
q = q.Where(t =t.Field1==1);
if (condition2)
q = q.Where(t =t.Field2==2);

Table1 has a sub table. Based on a condition I want find the Table1 records
that have one or more Table2 records. If I were using sql I would do
something like this:

select * from Table1 t1 where exists (select * from Table2 t2 where
t1.id=t2.id and t2.field1='somevalue')

How can I do this in LINQ given that I have added the above where clauses
based on those conditions?
Use the Queryable.Any extension method:
q=q.Where(t=>t.Table2s.Any(t2=>t2.Field1==someValu e));

FB
--
------------------------------------------------------------------------
Lead developer of LLBLGen Pro, the productive O/R mapper for .NET
LLBLGen Pro website: http://www.llblgen.com
My .NET blog: http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
------------------------------------------------------------------------
Jul 24 '08 #2
Thanks a lot for your help. This was exactly what I was looking for.

Thanks,
Nick
Jul 24 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

28 posts views Thread by Marc Gravell | last post: by
1 post views Thread by =?Utf-8?B?UGVkcm8=?= | last post: by
8 posts views Thread by Andy | last post: by
2 posts views Thread by Mucahit ikiz | last post: by
reply views Thread by =?Utf-8?B?SHlwZXJjb2Rlcg==?= | last post: by
14 posts views Thread by thj | last post: by
13 posts views Thread by Dan Tallent | last post: by
2 posts views Thread by shapper | last post: by
1 post views Thread by jbot | last post: by
reply views Thread by XIAOLAOHU | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.