linq to sql concatenate - ListBox的FirstName和LastName

use*_*727 3 linq linq-to-sql

我正在努力让以下工作.我有一个包含Fields FirstName,LastNameDoctorId的表.我想使用Linq to SQL填充.net ListBox.这是我找到和借用的东西:

在一个我称为DALClass的课程中:

public List<Doctor> GetListDoctorsNames()
{
  using (var db = new WaitListDataContext())
  {
    return (from c in db.Doctors
            select new
            {
              FullName = c.FirstName + " " + c.LastName,
              DoctorId = c.DoctorId
            }
            ).ToList<Doctor>;
  }
}
Run Code Online (Sandbox Code Playgroud)

该错误与").ToList;"有关.线.错误是:

错误1无法将方法组"ToList"转换为非委托类型"System.Collections.Generic.List".你打算调用这个方法吗?问:\ myapp\WaitList\App_Code\DALClass.cs 37 16问:\ myapp\WaitList \

我不确定我是不是应该放<String>而不是<Doctor>.我试过了,它不起作用.

p.s*_*w.g 5

您的查询返回一个匿名类型,而您实际上并没有调用该ToList方法.您可能需要指定数据类型select子句,并ToList使用括号调用方法,如下所示:

return 
    (from c in db.Doctors
     select new Doctor
     {
        FullName = c.FirstName + " " + c.LastName,
        DoctorId = c.DoctorId
     })
    .ToList<Doctor>(); // or just .ToList();
Run Code Online (Sandbox Code Playgroud)

更新

要解决第二个错误(" 'Doctor'不包含'FullName'的定义 "),问题是您没有在您的上定义任何此类属性Doctor.

您可以尝试定义一个单独的属性Doctor,但我不确定Linq-to-SQL是否允许这样做.您也可以重复使用其中一个现有属性(例如LastName),但听起来并不是特别优雅.

我建议设计一个单独的实体(通常你用匿名类型完成它,但是因为看起来你是从方法中返回的,所以如果你关心类型安全,这不是一个选项):

public class DisplayDoctor
{
    public string FullName { get; set; }
    public int DoctorId { get; set; }
}

return 
    (from c in db.Doctors
     select new DisplayDoctor
     {
        FullName = c.FirstName + " " + c.LastName,
        DoctorId = c.DoctorId
     })
    .ToList<DisplayDoctor>(); // or just .ToList();
Run Code Online (Sandbox Code Playgroud)