Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return list using select new in LINQ

Tags:

c#

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?

like image 683
Sami Avatar asked Jun 16 '11 09:06

Sami


People also ask

Does LINQ select return new object?

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.

What does select in LINQ return?

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.

How do I select a query in LINQ?

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.

How does select work in LINQ?

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.


1 Answers

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();     } } 
like image 59
Muhammad Hasan Khan Avatar answered Sep 19 '22 15:09

Muhammad Hasan Khan