linq query help

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?Tmljaw==?=

    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='some value')

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

    Thanks,
    Nick
  • Frans Bouma [C# MVP]

    #2
    Re: linq query help

    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='some value')
    >
    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==som eValue));

    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#)
    ------------------------------------------------------------------------

    Comment

    • =?Utf-8?B?Tmljaw==?=

      #3
      Re: linq query help

      Thanks a lot for your help. This was exactly what I was looking for.

      Thanks,
      Nick

      Comment

      Working...