【问题标题】:Quering with Linq in c# [closed]在 C# 中使用 Linq 进行查询 [关闭]
【发布时间】:2013-12-18 08:09:58
【问题描述】:

我需要计算 table1 中的记录,但条件是 我不应该计算 table1 中外键存在于 table2 中的记录。 我只想要 table1 中不在 table2 中的记录数
我想做的是c#-linq。

假设我有这张桌子

ID           Text               userId
--           ----               ------
1            hi! this is me     5
2            hey                5
3            no no              5

还有第二张桌子

pkid      fkId 
----      ----      
5          1          
6          1         
7          1

我想要 table1 中 userId=5 的所有记录,但不想要 table2 中外键为 table1 的记录

【问题讨论】:

  • 你能证明你想用 Linq 做这个吗?

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


【解决方案1】:
var result = table1
             .Where(x => x.userId == 5 && !table2
                                          .Any(y => y.fkId == x.ID))
             .Count();

Enumerable.Where 给出条件为true 的序列的所有元素。 如果至少有一个元素满足条件,Enumerable.Any 将产生 true。而Enumerable.Count 就是:序列中的元素个数。

【讨论】:

  • 很好的答案。谢谢你
  • 你能告诉我另外一种情况吗?那是相反的。现在我只想从表 1 中获取 pkId 作为 fkid 存在于表 2 中的记录
【解决方案2】:

也许你可以使用一个简单的 where 语句:

IList<string> cListOne = null;
IList<string> cListTwo = null;

IList<string> cListThree = cListOne.Where(Item => cListTwo.Contains(Item) == false).ToList();

简单地用你的类替换字符串并替换

cListTwo.Contains(Item) == false

你的逻辑!

【讨论】:

    【解决方案3】:

    试试这个:

    table1.Count(x => !table2.Any( y => y.id == x.id ));
    

    【讨论】:

      【解决方案4】:

      所以你有这样的表

      Table 1       Table2
      -------       ------
      x     1       1
      x     2       2
      x     3       3
      x  null       4
      

      要数你可以用这个

      var count = db.Table1.Count(t1 => !db.table2.Any(t2 => t1.TID == t2.ID))
      

      计算表1中外键不在表2主键中的所有。

      Count Method

      【讨论】:

        【解决方案5】:
        var count =  (from c in db.Table1 where c.userId == 5 && !(from o in db.Table2 select o.fkId).Contains(c.ID) select c).Count();
        

        【讨论】:

        • 请检查我的更新代码
        猜你喜欢
        • 2015-05-06
        • 1970-01-01
        • 2017-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多