Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq select fields

Tags:

c#

linq

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?

like image 395
Tom Gullen Avatar asked May 09 '26 23:05

Tom Gullen


1 Answers

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 };
like image 194
BrokenGlass Avatar answered May 12 '26 12:05

BrokenGlass



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!