同一类中的两个属性的列表

时间:2011-10-11 11:54:45

标签: c# linq

我有一个名为Session的实体类,它包含两个属性:LecturerOneLectureTwo。我想在LecturerOneLecturerTwo中创建所有不同名称的联合:

我得到LecturerOne工作。

public List<string> ListLecturer()
{
    var lecturerNames = (from s in db.Sessions                
                         select s.LecturerOne).Distinct();

    List<string> lecturerList = lecturerNames.ToList(); 
    return lecturerList;
}

2 个答案:

答案 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();