使用 Linq 查询而不是 Contains 运算符来解决性能问题
我必须提取 ID 在列表中的所有客户
我有一个 CustomerID 列表
List custidlist=new List{1,2,3....etc.}();
我有编写一个 linq 查询来获取 id 在上述列表
custidlist 中的所有客户。
var customer=db.Customers.Where(c=> custidlist.包含(c.customerid));
使用Contains在性能问题上并不好。
我们可以使用像这样的比较运算符
varcustomers=db.Customers.Where(c=> custidlist.Compare(c.customerid)); ???
我听说比较最适合性能
I have to Pull all customers whose ids are in the list
I have a list of CustomerID`s
List custidlist=new List{1,2,3....etc.}();
i have to write a linq query to get all customers whose id`s are in the above list
custidlist.
var customers=db.Customers.Where(c=> custidlist.Contains(c.customerid));
Using Contains is not good in performance issue.
Can we use COMPARE OPERATOR LIKE THIS
var customers=db.Customers.Where(c=> custidlist.Compare(c.customerid)); ????
I Heard Compare is best for Performance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于这是 Linq to SQL / Entities,因此您的 Linq
Contains
查询将被转换为大致如下的 SQL 语句:不仅不支持您的其他建议,而且您也无法做得比此 SQL 性能更好。
Since this is Linq to SQL / Entities your Linq
Contains
query will be translated to a SQL statement roughly like:Not only is your other suggestion not supported, but also you cannot do any better than this SQL performance wise.
当您在 Linq to SQL 中编写 Contains 查询时,它将作为 SQL 中的 in 查询被触发,并且在数据库上运行查询应该是最快的。
但对此需要注意的是,要记住 in 查询可能对数量有限制我认为 sql server 中的实体大约有 2000+,解决这个问题的方法是批量查询。
When you write a Contains query in Linq to SQL it iwll be fired as an in query in SQL and running your query on the databse should be the fastest..
one caveats to this though is to remember in query might have a limit on the number of entities I think its around 2000+ in sql server and the way around this would be to batch your query.