开发者

List of two attributes in same class

开发者 https://www.devze.com 2023-04-12 09:59 出处:网络
I have an Entity Class calle开发者_如何学Cd Session and it containts two attributes:LecturerOne and LectureTwo. I want to create a union of all the distinct names in LecturerOne and LecturerTwo:

I have an Entity Class calle开发者_如何学Cd Session and it containts two attributes: LecturerOne and LectureTwo. I want to create a union of all the distinct names in LecturerOne and LecturerTwo:

I got just LecturerOne working.

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

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


One option:

var list = db.Sessions.SelectMany(s => new string[] { s.LecturerOne,
                                                      s.LecturerTwo })
                      .Distinct()
                      .ToList();

I don't know offhand how EF will treat that, but it's worth a try...

Alternatively, similar to Jamiec's answer but IMO simpler:

var list = db.Sessions.Select(s => s.LecturerOne)
                      .Union(db.Sessions.Select(s => s.LecturerTwo))
                      .ToList();

(Union already returns distinct results, so there's no need to do it explicitly.)


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号