Reputation: 2554
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.
Upvotes: 5
Views: 1105
Reputation: 532745
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()) {
...
}
Upvotes: 2