Reputation: 61729
Just experimenting with Linq:
DataClassesDataContext db = new DataClassesDataContext();
var q = from p in db.tblBlogEntries select p;
foreach (var customer in q)
{
Response.Write(customer.ID + " " + customer.title + "\n");
}
Works fine, but I can only seem to return 1 field, or all of them. How do I select say, p.ID
and p.title
, and nothing else?
Upvotes: 2
Views: 268
Reputation: 160852
you need a projection to an anonymous type to only return the "parts" that you want:
var q = from p in db.tblBlogEntries select new { p.ID, p.Title };
Alternatively you could also define a new class that only has the subset of the properties you want. This might be beneficial if you want to return instances of the projection, since anonymous types can only be used in local scope:
var q = from p in db.tblBlogEntries
select new BlogTitleAndId() { ID = p.ID, Title = p.Title };
Upvotes: 8
Reputation:
How about this:
DataClassesDataContext db = new DataClassesDataContext();
var q = from p in db.tblBlogEntries select new { ID = p.ID, title = p.title };
foreach (var customer in q)
{
Response.Write(customer.ID + " " + customer.title + "\n");
}
This part new { ID = p.ID, title = p.title }
creates an anonymous class with members ID
and title
. You can add members for any column you wish and the types will be deduced automatically. Getting all the fields isn't that big a deal though. This article provides more information and a sample similar t yours.
Upvotes: 0
Reputation: 2721
Something like this...
DataClassesDataContext db = new DataClassesDataContext();
var q = from p in db.tblBlogEntries select new { Id = p.ID, Title = p.title };
foreach (var customer in q)
{
Response.Write(customer.ID + " " + customer.title + "\n");
}
Upvotes: 1
Reputation: 26495
Instead of "select p"
Use:
var q = from p in db.tblBlogEntries select new { Column1 = p.Column1, Column2 = p.Column2 };
The new{} makes a inline class, so you can select whichever columns you need.
Upvotes: 1