【问题标题】:Getting Selective data Using Linq in C#在 C# 中使用 Linq 获取选择性数据
【发布时间】:2013-12-18 10:13:17
【问题描述】:

我有两个表,我想要这样的数据。我想在 林克。可以吗?

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

我想从表一中获取记录

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;

【问题讨论】:

  • 请包含您尝试过的代码。
  • 能否请您检查一下是否可行

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


【解决方案1】:

如果你想计算,你可以在两个表中使用join 来创建这个查询,然后计算,作为示例:

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();

【讨论】:

  • 只需添加一件事,否则上面的查询没问题。实际上情况是发送者和接收者可以是同一个用户。可能存在接收者存在但发送者不存在的情况,反之亦然,因此在上述查询中,我还想添加 where t1.Receiverid=2 或 t1.senderid=2
  • 没问题,只需在where 语句中使用OR 运算符|| 添加此条件即可。看看我的编辑!
  • 对不起,我再次打扰您,但参考您的查询,我的完整查询已发布在上面,实际上是我想要的,还请检查表格,我已更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-05
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多