Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only few columns in LINQ query

Tags:

c#

linq

I have the following query

 var xyz = from a in prod.Categories
                           where a.CatName.EndsWith("A")
                           select a;

However all the columns are returned in this case. How do i rewrite query so that only few columns are returned like a.CatName, a.CatID, a.CatQty and so on.

like image 943
Jeju Avatar asked Aug 12 '10 09:08

Jeju


People also ask

How to select multiple Dept and name fields in LINQ?

var selectedLst=from item in employeesLst select item.Name; But if now we want to select multiple Dept and Name fields then we can not use this since this will be invalid syntax in LINQ: var selectedLst=from item in employeesLst select item.Id,item.Name; to handle such scenario we can use the anonymous type using the following syntax:

How can you tell if a SELECT statement is a LINQ?

We can tell because there are no specified properties in the Select. Even though this statement looks more complex it’s only three lines and looks somewhat like a SQL statement. But it’s really a LINQ (Language Integrated Query) statement, specifically a LINQ to Entities statement. This LINQ statement will be translated into this SQL statement:

Can I use the person class in a LINQ query?

However, you should use an instance of the DataContext for querying (it's not obvious that DataContext is an instance or the type name from your query): Apparently, the Person class is your LINQ to SQL generated entity class.

How can we specify columns in a SQL query?

How can we specify columns in our query? One easy way is to specify an anonymous type. Don’t be confused by the $2 word wizardry. Just think of an anonymous types as a way to put data into an object without defining an object. We can do that simply by using the “new” operator and selecting the properties from the object that we need.


1 Answers

var xyz = from a in prod.Categories
                           where a.CatName.EndsWith("A")
                           select new { CatName=a.CatName, CatID=a.CatID, CatQty = a.CatQty};
like image 156
Ben Robinson Avatar answered Oct 16 '22 13:10

Ben Robinson