How return distinct records using LINQ

How can I get my code below to return distinct records. The relationship between courses and coursesstructures is one to many

public IQueryable<object> GetCoursesDetails()
{
    var query = (from c in db.Courses
                 from cs in db.CoursesStructures.Where(cs => cs.CourseID == c.CourseID).DefaultIfEmpty()
                 select new
                 {
                     CourseID = c.CourseID,
                     CourseName = c.CourseName,
                     CoursesStructures = db.CoursesStructures.Select(x => new
                     {
                         CourseStructureID = x.CourseStructureID,
                         CourseID = x.CourseID,
                         StructureName = x.StructureName
                     }).Where(k => k.CourseID == c.CourseID)
                 });

    return query;
}
Jon Skeet
people
quotationmark

It seems to me that the problem is your use of the second from clause - you're not using cs at all, so why bother with it? It's just introducing the duplication, because you're selecting one result per matching course structure.

I would actually use a join ... into clause, and then use the result in your select:

var query = from c in db.Courses
            join cs in db.CoursesStrutures
              on c.CourseID equals cs.CourseID
              into structures
            select new
            {
                c.CourseID,
                c.CourseName,
                CoursesStructures = structures.Select(x => new
                {
                    x.CourseStructureID,
                    x.StructureName
                }
            };

(I've removed the CourseID from the nested anonymous type, as it's obviously going to be the same as the outer one anyway... I've also used projection initializers to simplify the code - that's where you can shorten Foo = x.Foo to just x.Foo in an anonymous type initializer.)

people

See more on this question at Stackoverflow