2
SELECT userid FROM userTable 
WHERE userid in (select writeuserid FROM boardTable)

C# LINQ expressions, how to use a query?

I have been using EF4. userTable, boardTable is connected to the DbContext.

user2214027
  • 49
  • 1
  • 6

3 Answers3

4

Why not have two different LINQ queries, so that your inner query doesn't execute for each iteration of the outer query.

var query1 = (from t in dbContext.boardTable
            select t.writeuserid).ToArray();

var query2 = from r in dbContext.userTable
             where query1.Contains(r.userid)
             select r.userid;

If your situation is as simple as in the question then you cause join in linq

Habib
  • 219,104
  • 29
  • 407
  • 436
  • http://stackoverflow.com/questions/527819/linq-sub-select or check this one too – isioutis Apr 01 '13 at 08:02
  • +1 just for spend more effort than OP to solve this problem.. – Soner Gönül Apr 01 '13 at 08:03
  • Using ToArray() may be a bit dangerous if the amount of data is very large, since it will cause EF to materialize the entire array. A join may be more suited for that purpose. – Pablo Romeo Apr 01 '13 at 08:06
  • 2
    @PabloRomeo, actually I wasn't sure about the exact requirement of the OP, so presented him/her with the above option, also added a link for joins in linq – Habib Apr 01 '13 at 08:12
1

Assume in here you use Entity FrameWork, so you can use Join to get the result, below is to use the lambda expression:

var result = dbContext.Users.Join(dbContext.Boards, 
                                  user => user.UserId, 
                                  board => board.WriteUserId,
                                  (u, b) => u.UserId);
cuongle
  • 74,024
  • 28
  • 151
  • 206
1

why not using join?

var result = (from u in dbcontext.userTable 
join u1 in dbcontext.boardTable on u.userid equals u1.writeuserid
select u.userid).FirstOrDefault();

if (result != null)
 // do anything else
else
 // user not exists
eRiCk
  • 43
  • 1
  • 8