返回按FirstName排序的列表?

时间:2013-09-16 17:24:29

标签: linq

鉴于此:

public static List<DoctorFullName> GetListDoctorsNames()
  {
  using (var db = new WaitListDataContext())
  {
     return db.Doctors.Select(c => new DoctorFullName()
      {
        FullName = c.FirstName + " " + c.LastName,
        DoctorId = c.DoctorId
      }).ToList();
  }
}

如何返回按FirstName排序的列表?

3 个答案:

答案 0 :(得分:1)

public static List<DoctorFullName> GetListDoctorsNames()
  {
  using (var db = new WaitListDataContext())
  {
     return db.Doctors.OrderBy(doc => doc.FirstName).Select(c => new DoctorFullName()
      {
        FullName = c.FirstName + " " + c.LastName,
        DoctorId = c.DoctorId
      }).ToList();
  }
}

答案 1 :(得分:0)

您应该可以订购:

public static List<DoctorFullName> GetListDoctorsNames()
  {
  using (var db = new WaitListDataContext())
  {    
     return db.Doctors
              .OrderBy(d => d.FirstName)
              .Select(c => new DoctorFullName()
                  {
                    FullName = c.FirstName + " " + c.LastName,
                    DoctorId = c.DoctorId
                  })
              .ToList();
  }
}

答案 2 :(得分:0)

只需添加.OrderBy()子句即可。您只能在FirstName

之前按.Select()排序
return db.Doctors
         .OrderBy(c => c.FirstName)
         .Select(c => new DoctorFullName()
  {
    FullName = c.FirstName + " " + c.LastName,
    DoctorId = c.DoctorId
  }).ToList();

或者您可以在.Select()之后对其进行排序,因为您的新字段始终以FirstName值开头:

return db.Doctors.Select(c => new DoctorFullName()
  {
    FullName = c.FirstName + " " + c.LastName,
    DoctorId = c.DoctorId
  })
  .OrderBy(c => c.FullName)
  .ToList();

The IEnumerable<T> interface提供了许多操作集合和返回修改后的集合的方法,因此它们可以通过多种不同的方式链接在一起。