jack_c jack_c - 1 month ago 8
C# Question

How to convert LINQ Query Generic List of Anonymous objects to IEnumerable<object>

I have the following Repository Method and I am trying to convert a LINQ query ToList result to my return type with no avail. Any advice would be appreciated.

public class ProjectRepository : IProjectRepository
{
IDBEntities DBContext;
public ProjectRepository(IDBEntities db)
{
DBContext = db;
}
public IEnumerable<project> SelectAll(bool? is_debug_mode, int? performed_by_id)
{
var projects = (from p in DBContext.projects
join o in DBContext.organizations on p.organization_id equals o.organization_id
join m in DBContext.members on o.organization_id equals m.organization_id
where m.member_id == performed_by_id
select new
{
p
}).ToList();
return (IEnumerable<project>)projects;
}
}


The error I receive is:


Unable to cast object of type
'System.Collections.Generic.List
1[<>f__AnonymousType2
1[NameSpace.Data.project]]'
to type
'System.Collections.Generic.IEnumerable`1[NameSpace.Data.project]'.

Answer

Assuming that the p in linq query is of type project

var projects = (from p in DBContext.projects
                join o in DBContext.organizations on p.organization_id equals o.organization_id
                join m in DBContext.members on o.organization_id equals m.organization_id
                where m.member_id == performed_by_id
                select p).ToList();
return projects;