Return list using select new in LINQ

This is my method which gives me error.

public List<Project> GetProjectForCombo()
{
    using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
    {
        var query = from pro in db.Projects
                    select new { pro.ProjectName, pro.ProjectId };

        return query.ToList();
    }
}

If i change it with this:

public List<Project> GetProjectForCombo()
{
    using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
    {
        var query = from pro in db.Projects
                    select pro;

        return query.ToList();
    }
}

Then it works fine with no errors.

Can you please let me know that how I can return only ProjectId and ProjectNam?


Method can not return anonymous type. It has to be same as the type defined in method return type. Check the signature of GetProjectForCombo and see what return type you have specified.

Create a class ProjectInfo with required properties and then in new expression create object of ProjectInfo type.

class ProjectInfo
{
   public string Name {get; set; }
   public long Id {get; set; }
}

public List<ProjectInfo> GetProjectForCombo()
{
    using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
    {
        var query = from pro in db.Projects
                    select new ProjectInfo(){ Name = pro.ProjectName, Id = pro.ProjectId };

        return query.ToList();
    }
}

public List<Object> GetProjectForCombo()
{
   using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
   {
     var query = db.Project
     .Select<IEnumerable<something>,ProjectInfo>(p=>
                 return new ProjectInfo{Name=p.ProjectName, Id=p.ProjectId);       

     return query.ToList<Object>();
   }

}