开发者

Linq select fields

Just experimenting with Linq:

    DataClassesDataContext db = new DataClassesDataCo开发者_StackOverflowntext();
    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?


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 };


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.


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");
}


var q = from p in db.tblBlogEntries select new {p.ID, p.Title}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜