【问题标题】:Getting Max ID from 2 tables with LINQ 2 SQL使用 LINQ 2 SQL 从 2 个表中获取最大 ID
【发布时间】:2011-10-17 22:16:49
【问题描述】:

我有一个“var”,其中包含使用 LINQ to SQL 的两个表的结果。我需要获取 MAX(table1.ID)。但我做不到:

myVar.table1.ID.Max()

因为 myVar 不知道它所持有的对象。该语法应该是什么样的?

编辑:

完整的查询是:

var myVar = from table1 in db.table1s
            join table2 in db.table2s
            on table1.empid equals table2.empid
            where table2.deptid = deptid
            select table1

返回几个结果。我想要最大 table1.ID 行。

【问题讨论】:

  • 请向我们展示更多您的代码。目前还不清楚你在做什么。见tinyurl.com/so-hints
  • 好的,如果有帮助,请告诉我。谢谢。
  • 请记住,LINQ 实际上是一组要在集合上执行的方法,而不是单个参数。无论您计划使用什么聚合/谓词/等 LINQ 方法,都将在您的集合对象(IQueryable 或 IEnumerable)上执行。 Lambda/匿名方法只是提供了一种简单的方法来创建谓词 (Func)、选择器 (Func) 或操作 (Action) 内联委托。

标签: c# .net linq-to-sql c#-3.0


【解决方案1】:

好的,看起来你想要:

var maxId = myVar.Max(x => x.ID);

或者如果您可能没有任何条目:

var maxId = myVar.Max(x => (int?) x.ID);

如果maxId 为空,则null 将是null

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多