Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any Way to Use a Join in a Lambda Where() on a Table<>?

Tags:

c#

.net

linq

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.

like image 360
Christopher Garcia Avatar asked Nov 05 '22 15:11

Christopher Garcia


1 Answers

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()) {
    ...
}
like image 198
tvanfosson Avatar answered Nov 11 '22 13:11

tvanfosson