我有一个名为Session
的实体类,它包含两个属性:LecturerOne
和LectureTwo
。我想在LecturerOne
和LecturerTwo
中创建所有不同名称的联合:
我得到LecturerOne工作。
public List<string> ListLecturer()
{
var lecturerNames = (from s in db.Sessions
select s.LecturerOne).Distinct();
List<string> lecturerList = lecturerNames.ToList();
return lecturerList;
}
答案 0 :(得分:3)
一个选项:
var list = db.Sessions.SelectMany(s => new string[] { s.LecturerOne,
s.LecturerTwo })
.Distinct()
.ToList();
我不知道EF会如何对待它,但值得一试......
或者,类似于Jamiec的回答,但IMO更简单:
var list = db.Sessions.Select(s => s.LecturerOne)
.Union(db.Sessions.Select(s => s.LecturerTwo))
.ToList();
(Union
已经返回不同的结果,因此无需明确地执行此操作。)
答案 1 :(得分:2)
var lecturerOnes = (from s in db.Sessions
select s.LecturerOne);
var lecturerTwos = (from s in db.Sessions
select s.LecturerTwo);
List<string> lecturerList = lecturerOnes.Union(lectureTwos).ToList();