如何在IQueryable中首先订购一件商品

时间:2014-08-01 15:12:37

标签: c# linq sorting

我有一个返回IQueryable的实体的linq。我需要将自我加入(e.empid == empid)作为第一项。我该怎么办?

public IQueryable<vmEmp> GetEmpUnder(string empid)
{
    var dataContext = new Entities();         
    var Emp = from e in dataContext.lstEmp.Where(e => e.Supervisor == empid || e.empid == empid)
                select new vmEmp
                {
                    EmpId = e.empid,
                    Name = e.LName + ", " + e.FName
                };

    var under = Emp.ToList().Where(e => DirectCount(e.EmpId) > 0);
    Emp = under.AsQueryable<vmEmp>();

    return Emp;
}

1 个答案:

答案 0 :(得分:3)

您可以将orderby与布尔值一起使用,但请注意它在true之前命令为false,因此您需要使用descending。另请注意,您可以将Where合并到查询的其余部分:

var Emp = from e in dataContext.lstEmp
          where e.Supervisor == empid || e.empid == empid
          orderby e.empid == empid descending
          select new vmEmp
          {
              EmpId = e.empid,
              Name = e.LName + ", " + e.FName
          };

或者您可以进行两个查询并将它们连接在一起,如下所示:

var Emp = 
    (from e in dataContext.lstEmp
     where e.Supervisor == empid
     select new vmEmp
     {
         EmpId = e.empid,
         Name = e.LName + ", " + e.FName
     }).Concat(
     from e in dataContext.lstEmp
     where e.empid == empid
     select new vmEmp
     {
         EmpId = e.empid,
         Name = e.LName + ", " + e.FName
     });