代码之家  ›  专栏  ›  技术社区  ›  user215675

C LINQ查找值

  •  1
  • user215675  · 技术社区  · 15 年前

    我想通过比较部门表返回未找到员工表的部门编号。

    个人表

    ID        name   salary     job              commision  DeptID 
    --------------------------------------------------------------
    P001      Jon       2000      Manager       NULL       1
    P002      Skeet     1000      Salesman      2000       1
    P003      James     2340      Developer     NULL       2
    P004      greed     4500      Developer     NULL       2
    P005      Joel      1330      Salesman      1200       1
    P006      Deol      5000      Architect     NULL       2
    

    部门表

    DeptID  DeptName
    
        1   Management
        2   Software  
        3   ERP       
    

    SQL

    select DeptId from dept
    
    where deptId not in (select deptid from person)
    

    当我试图执行以下代码时

    林克

    var qry = from n in context.Persons
              where n.DeptID !=
              (from m in context.Depts select m.DeptId)
               select new { DeptID = n.DeptID };
    

    我收到以下错误

    接线员!='不能应用于'int?'类型的操作数。和“system.linq.iqueryable”

    4 回复  |  直到 15 年前
        1
  •  2
  •   Jonatan Lindén    15 年前

    建议重新措辞:

    var q = from m in context.Depts
            where
            !context.Persons.Select(p => p.DeptID).Contains(m.DeptID)
            select new { DeptID = m.DeptID };
    
        2
  •  3
  •   kwcto    15 年前
    var qry = from n in context.Persons
              where n.DeptID !=
              (from m in context.Depts select m.DeptId).FirstOrDefault()
               select new { DeptID = n.DeptID };
    

    您正在尝试将deptid与集合1或多个部门ID进行比较。即使一个deptid在逻辑上只有一个结果,在语法上,您也需要指定您想要第一次命中。

        3
  •  2
  •   Agent_9191    15 年前

    听起来SQL中的deptid字段设置为允许空值。在这种情况下,你可能会想要这样的东西:

    var qry = from n in context.Persons
              where n.DeptID.Value !=
              (from m in context.Depts select m.DeptId)
               select new { DeptID = n.DeptID.Value };
    
        4
  •  1
  •   Canavar    15 年前

    我想应该是那样的。我尝试先获取deptid的列表,然后实现一个not-in-with-contains:

    var deptIDs = context.Persons
         .Where( p => !context.Depts
                 .Select(d => new {DeptID = d.DeptID})
                 .Contains( p.DeptID ) 
                )
         .Select( p => new { DeptID = n.DeptID } );