2013-09-16 38 views
1

有鑑於此:返回按名字排序的列表?

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(); 
    } 
} 

我怎麼能回到通過名字排序的名單?

回答

0

只需添加一個.OrderBy()條款。您可以通過僅FirstName.Select()之前進行排序:

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

或者因爲你的新領域與FirstName值開始,反正你可以在你的.Select()後排序,:

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

The IEnumerable<T> interface提供了大量的方法來操作一個集合並返回修改後的集合,所以它們可以用很多不同的方式鏈接在一起。

+0

啊,謝謝你的選擇並解釋它們。 – user995727

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(); 
    } 
} 
+0

謝謝,就是這樣!我會盡快給予答覆。你能解釋一下,「doc => doc.FirstName)」嗎?我是C#和Linq to SQL的新手。 – user995727

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(); 
    } 
}