简体   繁体   English

Linq-加入ID为!=的地方,选择新的+不同的吗?

[英]Linq - Join where ID's !=, select new + distinct?

I have the following classes. 我有以下课程。

Course; 课程;

 public class Course
{
    //pk
    public int Id{ get; set; }
    public int SourceCourseId { get; set; }
    public string Name { get; set; }
}

Registration 注册

public class Registration
{
    //primary key
    public int Id { get; set; }
    //...more fields
    public int CourseId { get; set; }
}

I want to obtain a collection of annonymous objects with the two fields below for all Courses that are Distinct in the registrations table that are not in the Courses table. 我想获取以下两个字段的匿名对象的集合,这些字段用于不在课程表中的注册表中与众不同的所有课程。

var distinctCourses = (from registration in db.Registrations
                       join courses in db.Courses on registration.CourseId equals courses.SourceCourseId
                       where registration.CourseId != courses.SourceCourseId
                       select new
                            {
                                SourceCourseId = registration.CourseId,
                                Name = registration.CourseName,

                            }).Distinct().ToList();

For some reason the above is returning 0... Any suggestions? 由于某种原因,以上返回0 ...有什么建议吗?

try a left join: 尝试左联接:

var query = from r in registrations
join c in courses on r.CourseId equals c.id into newCourses
from nullCourse in newCourses.DefaultIfEmpty()
where nullCourse == null
select new { }

Edit - per comment from Alex : Also, your where clause needs to change to 编辑-根据Alex的评论:另外,您的where子句需要更改为

where nullCourse == null

Edit - changed join columns and added correct where clause. 编辑-更改了连接列,并添加了正确的where子句。

Edit - group registrations on CourseID so they will be distinct 编辑-在CourseID上对注册进行分组,这样它们就可以不同

var distinctCourses = 
    (from registration in db.Registrations 
     group registration by registration.CourseId into grp
     from reg in grp
     join courses in db.Courses on reg.CourseId equals courses.SourceCourseId into newCourses
     from nullCourse in newCourses.DefaultIfEmpty()
     where nullCourse == null
     select new
     {
        SourceCourseId = reg.CourseId,
        Name = reg.CourseName,

     }).ToList();

Try this 尝试这个

var result = Registrations.GroupJoin(Courses,r=>r.CourseId,c=>c.SourceCourseId,
                            (k,g) => new {k,g})
                            .Where(x=>x.g.Count()==0)
                            .Select(s=> new {id=s.k.CourseId,name=s.k.CourseName});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM