tcode
tcode

Reputation: 5105

Linq to Entities Distinct on Column without Anonymous Type

I am using Entity Framework 5.0 and I wish to return a list of objects, however, I want to perform a DISTINCT on one of the properties on each object within the list.

I know there are a few questions similar to mine already on Stackoverflow, however, I am still struggling with this one.

Currently my query looks like this

public IList<tblcours> GetAllCoursesByOrgID(int id)
{
     return _UoW.tblcoursRepo.All.Where(c => c.tblCourseCategoryLinks.Any(cl => cl.tblUnitCategory.tblUnit.ParentID == id))
            .OrderBy(c => c.CourseTitle)
            .ToList();
}

However, I need to perform a DISTINCT on the property MainHeadingID to remove any objects already with the same ID, but still returning the entire object with all its properties.

Preferably, I would like to return IList, as you can see from my method, and not an Anonymous Type.

Any help with this is greatly appreciated.

Thanks.

Upvotes: 1

Views: 1942

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

Have you tried using GroupBy?

_UoW.tblcoursRepo.All.GroupBy(c => c.MainHeadingId)
                     .Select(g => g.FirstOrDefault())

Upvotes: 5

Related Questions