在C#中使用Linq获取选择性数据

时间:2013-12-18 10:13:17

标签: c# asp.net asp.net-mvc linq sql-server-2005

我有两张桌子,我想以这样的方式获取数据。我想进行此查询 LINQ。可以吗?

Table1

pkId    SenderId  ReceiverId
   1           2           5
   2           2           2
   3           2           7
   4           3           2

Table 2

pkTbl2Id       fkId    fkUserId
  1              1        2
  2              2        7

我想从表1中获取

的记录
table1.SenderId == 2 || table1.ReceiverId == 2 && Table 2.fkId == Table1.pkId

答案是 第一张表的第一个记录 即

1              2                5

我用过了

    return DB.table1
        .Where(x => 
            x.receiverId == 2 
            || x.senderID == 2 
            && DB.table2.Any(y => y.fkid == x.pkid))
        .Count();



 var ll = from rs in DB.tblMessages
                         join mm in DB.tblLogs
                             on rs.pkMessageId equals mm.fkMessageId
                         where rs.fkReceiverUserId == UserId || rs.fkSenderUserId == UserId && mm.fkUserID == UserId
                         select rs;

1 个答案:

答案 0 :(得分:1)

如果您想要计算,可以在两个表中使用join来创建此查询,然后使用{count>来计算样本:

var query = from t1 in DB.table1
            join t2 in DB.table2 on t1.pkId equals t2.fkId
            where t1.ReceiverId == 2 || t1.SenderId == 2 
            select t1;

var countResult = query.Count();