绩效:.加入vs.包含

编程入门 行业动态 更新时间:2024-10-21 19:02:56
本文介绍了绩效:.加入vs.包含-对实体的Linq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Linq对实体进行查询,以查询数据库以获取int列表以进行进一步处理.我有两种获取列表的方法,如下所示:

I am using Linq to entities to query the database to get the list of int for further processing. I have two ways to get the list as below:

第一个是:

List<int> lstBizIds = new List<int>() { 1, 2, 3, 4, 5 }; List<int> lstProjectIds = context.Projects.Where(x => lstBizIds.Contains(x.businessId)).Select(x => x.projectId).ToList();

第二个是

List<int> lstBizIds = new List<int>() { 1, 2, 3, 4, 5 }; List<int> lstProjectIds = context.Projects.Join(lstBizIds, p => p.businessId, u => u, (p, u) => p.projectId).ToList();

现在我的问题是,哪种方法在性能上更好?如果第一个列表(即lstBizIds)的大小增加,还会影响性能吗?如果会降低性能,请向我提出其他实施方式.

Now my question is which one of the methods above is better performance wise? Also does it affect the performance if the first list i.e. lstBizIds grows in size? Suggest me other ways of implementation as well if that are performance reducing.

推荐答案

您应该使用Contains,因为EF可以产生更有效的查询.

You should go with Contains, because EF can produce a more efficient query.

这将是SQL连接:

SELECT Id FROM Projects INNER JOIN (VALUES (1), (2), (3), (4), (5)) AS Data(Item) ON Projects.UserId = Data.Item

这将是SQL包含的内容:

This would be the SQL Contains:

SELECT Id FROM Projects WHERE UserId IN (1, 2, 3, 4, 5, 6)

IN比JOIN更有效率,因为DBMS可以停止寻找IN的第一个匹配项. JOIN始终会完成,即使在第一个比赛之后也是如此.

IN is more efficient than JOIN because the DBMS can stop looking after the first match of the IN; the JOIN always finishes, even after the the first match.

您可能还想检查哪些查询实际发送到了数据库.您总是必须比较SQL,而不是LINQ代码(显然).

You might also want to check which queries are actually sent to the DB. You always have to compare the SQL, not the LINQ code (obviously).

更多推荐

绩效:.加入vs.包含

本文发布于:2023-06-03 10:05:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/473772.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绩效

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!