给定用户的MaxID

时间:2017-03-03 11:51:09

标签: c# entity-framework linq

从以下数据中我想获得EmpID 1100的MaxID

ID  | EmpId  
1   | 1002   
5   | 1100   
6   | 1109   
7   | 1100   
9   | 1100   
10  | 1250   
11  | 1250   
12  | 1100   

结果应该是

ID
9  

请帮忙

2 个答案:

答案 0 :(得分:0)

Try this,
`employee` is the table name and `ctx` is the `dbcontext` of EF

    var maxid=  (from p in ctx.employee
                 where p.empid== 1100
                 select p.Id).Max();

// you can use it like this 
   var nRow = (from f in db.FeeAccount where f.FeeMainUserID == maxid);

答案 1 :(得分:0)

你可以这样做。需要注意的重要事项是,您必须拥有元素才能在集合上运行Max

var recs = ctx.Employees.Where(e => e.EmpId == IdToBeSearched).Select(e => e.Id).ToList();
if(recs.Any())
{
    return recs.Max();
}

或者

var recs = ctx.Employees.Where(e => e.EmpId == IdToBeSearched).Select(e => e.Id).OrderByDescending().FirstOrDefault();