Linq 选择字段
只是尝试使用 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");
}
工作正常,但我似乎只能返回 1 个字段或全部字段。如何选择 p.ID
和 p.title
,而不选择其他内容?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要投影到匿名类型以仅返回“部分”您想要的:
或者,您也可以定义一个仅具有您想要的属性子集的新类。如果您想返回投影的实例,这可能会很有用,因为匿名类型只能在本地范围内使用:
you need a projection to an anonymous type to only return the "parts" that you want:
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:
代替“select p”
使用:
新的{} 生成一个内联类,因此您可以选择所需的任何列。
Instead of "select p"
Use:
The new{} makes a inline class, so you can select whichever columns you need.
像这样的东西...
Something like this...
var q = 从 db.tblBlogEntries 中的 p 选择新的 {p.ID, p.Title}
var q = from p in db.tblBlogEntries select new {p.ID, p.Title}
怎么样:
这部分
new { ID = p.ID, title = p.title }
创建一个带有成员ID
和title
的匿名类。您可以为任何您想要的列添加成员,类型将自动推导。不过,获得所有字段并不是什么大问题。 本文提供了更多信息和与您类似的示例。How about this:
This part
new { ID = p.ID, title = p.title }
creates an anonymous class with membersID
andtitle
. 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.