LINQ - 最小化返回的记录 - 编写这些表达式的正确方法
Employee 是一个示例实体类型。
var r1 = (from c in _ctx select c).Skip(5).Take(5);
// my intent is to pull the first record from the query
var r2 = (from c in _ctx select c).FirstOrDefault<Employee>();
// my intent is to pull the last record from the query.
// any good way to ask for the result back in the reverse
// order of the natural sort without specifing a field/property name?
var r3 = (from c in _ctx select c).LastOrDefault<Employee>();
这些是否会拉回整个记录(对象)然后进行过滤? 编写这些以使整行都是 LINQ 表达式的最佳方法是什么?
Employee is a sample entity type.
var r1 = (from c in _ctx select c).Skip(5).Take(5);
// my intent is to pull the first record from the query
var r2 = (from c in _ctx select c).FirstOrDefault<Employee>();
// my intent is to pull the last record from the query.
// any good way to ask for the result back in the reverse
// order of the natural sort without specifing a field/property name?
var r3 = (from c in _ctx select c).LastOrDefault<Employee>();
Do these pull back the entire records (objects) and then filter?
What is the best way to write these so that the whole line is a LINQ expression?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我相信(假设
_ctx
是一个DataContext
)生成的 SQL 会比较高效。我可以建议您在运行这些代码时运行 SQL Server Profiler 吗?
我认为对 r2 的查询将是一个简单的 SELECT TOP (1) 语句。
r1
有机会高效地使用:r3
看起来它可能只是选择全部并获取最后一条记录。尝试 Profiler 并查看:)
I believe that (assuming
_ctx
is aDataContext
) the SQL generated will be mildly efficient.Can I suggest that you run SQL Server Profiler while you run these bits of code?
I think the query for
r2
will be a simpleSELECT TOP (1)
statement.r1
has a chance of being efficient with:r3
looks like it may just select all and take the last record.Try Profiler and see :)
如果您使用 IQueryable,则意味着您创建将在远程源中运行的表达式树
请参阅 IQueryable和 IQueryable之间有什么区别和 IEnumerable?
好书工具 c# 3.0 in a NutShell、LinqPad、LINQ in Action
If you use IQueryable that means that you create a expression tree that will be run in the remote source
See What is the difference between IQueryable<T> and IEnumerable<T>?
Good books tools c# 3.0 in a NutShell,LinqPad, LINQ in Action
_ctx.Employees.Skip(5).Take(5)
,因为没有查询替代Skip
的方法调用,采取
、首先
等。IQueryable
is used. However, @Codesleuth can be right concerningr3
._ctx.Employees.Skip(5).Take(5)
, because there is no query alternative to method calls ofSkip
,Take
,First
, etc.你怎么知道最后一条记录是什么?什么决定顺序?不能先调用 OrderByDescending 然后获取 FirstOrDefault 吗?也许这会产生更快的查询。
How do you know what the last record is? What determines the order? Can't you make a call to OrderByDescending and then take the FirstOrDefault? Perhaps that would yield a quicker query.