tags:

views:

156

answers:

1

I'm in my first couple of days using Linq in C#, and I'm curious to know if there is a more concise way of writing the following.

MyEntities db = new MyEntities(ConnString);

var q = from a in db.TableA
        join b in db.TableB
        on a.SomeFieldID equals b.SomeFieldID
        where (a.UserID == CurrentUser && 
        b.MyField == Convert.ToInt32(MyDropDownList.SelectedValue))
        select new { a, b };

if(q.Any())
{
//snip
}

I know that if I were to want to check the existence of a value in the field of a single table, I could just use the following:

if(db.TableA.Where(u => u.UserID == CurrentUser).Any())
{
    //snip
}

But I'm curious to know if there is a way to do the lambda technique, but where it would satisfy the first technique's conditions across those two tables.

Sorry for any mistakes or clarity, I'll edit as necessary. Thanks in advance.

+2  A: 

Yes, you can do this with extension methods. Note that you might get a more concise query by filtering each table first, though I suspect SQL Server would optimize it that way anyway.

if (db.TableA.Where( a => a.UserID == CurrentUser )
      .Join( db.TableB.Where( b => b.MyField == Convert.ToInt32(MyDDL.SelectedValue) ),
             o => o.someFieldID,
             i => i.someFieldID,
             (o,i) => o )
      .Any()) {
    ...
}
tvanfosson
I get an exception from the above code stating "No overload for the method 'Join' takes '2' arguments".
lush
@lush -- sorry, I had the signature wrong. It takes two key selectors (outer and inner), then a selector for the result. In this case, I simply selected the outer object since it will eventually be translated into an ANY query. I also added a link to the MSDN page for the join extension method so you can see the alternate syntax.
tvanfosson