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.
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:
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:
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 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.
var xyz = from a in prod.Categories
where a.CatName.EndsWith("A")
select new { CatName=a.CatName, CatID=a.CatID, CatQty = a.CatQty};
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