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
?
While the LINQ methods always return a new collection, they don't create a new set of objects: Both the input collection (customers, in my example) and the output collection (validCustomers, in my previous example) are just sets of pointers to the same objects.
The Select() method invokes the provided selector delegate on each element of the source IEnumerable<T> sequence, and returns a new result IEnumerable<U> sequence containing the output of each invocation.
LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.
Select is used to project individual element from List, in your case each customer from customerList . As Customer class contains property called Salary of type long, Select predicate will create new form of object which will contain only value of Salary property from Customer class.
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With