Redian新闻
>
问一个linq to sql编程问题 (转载)
avatar
问一个linq to sql编程问题 (转载)# DotNet - 窗口里的风景
o*e
1
【 以下文字转载自 Database 讨论区 】
发信人: okeoke (let's okeoke @ okeoke.net), 信区: Database
标 题: 问一个linq to sql编程问题
发信站: BBS 未名空间站 (Wed Jun 29 03:07:54 2011, 美东)
假设有一个table User,primary key is ID(int), one field called Name
given a list of user ID, say HashSet ids
what's the most efficient way to get the list of user?
from u in Users
where ids.Contains(u.ID)
select u
this is the most basic way i can think of. I'm sure there is a better way.
I'm using linq to sql
many thanks!
avatar
c*t
2
YourDBDataContext db = new YourDBDataContext();
var users = from p in ids
join u in db.Users on p.Key equals u.id
select u;

【在 o****e 的大作中提到】
: 【 以下文字转载自 Database 讨论区 】
: 发信人: okeoke (let's okeoke @ okeoke.net), 信区: Database
: 标 题: 问一个linq to sql编程问题
: 发信站: BBS 未名空间站 (Wed Jun 29 03:07:54 2011, 美东)
: 假设有一个table User,primary key is ID(int), one field called Name
: given a list of user ID, say HashSet ids
: what's the most efficient way to get the list of user?
: from u in Users
: where ids.Contains(u.ID)
: select u

avatar
o*e
3
多谢老大,我原来也是想多半和join有关。
刚测试了一下,悲剧了
db.Users.Where(u => ids.Contains(u.ID)).ToList() 耗时 800ms
(from p in ids
join u in db.Users on p equals u.ID
select u).ToList();
居然用了超过4s,不知道哪里有问题
ids的长度是200,db.Users有差不多150k条记录
avatar
c*t
6
linq to sql is lazy execution; if the final SQL is IN, it should be faster;
My original idea is to avoid select entire table than join, which is very
bad.

,

【在 o****e 的大作中提到】
: 搜了一下,还是直接用contains快,linq to sql会把contains 翻译成 in:
: ...
: FROM [User] AS [t0]
: WHERE [t0].[ID] IN (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10,
: @p11, ... @p199)
: }
: 参考
: http://archive.msdn.microsoft.com/LinqtoSQLJoinExample
: http://coolthingoftheday.blogspot.com/2008/01/being-in-in-linq-

avatar
s*o
7
Sql Profiler may help

【在 o****e 的大作中提到】
: 多谢老大,我原来也是想多半和join有关。
: 刚测试了一下,悲剧了
: db.Users.Where(u => ids.Contains(u.ID)).ToList() 耗时 800ms
: (from p in ids
: join u in db.Users on p equals u.ID
: select u).ToList();
: 居然用了超过4s,不知道哪里有问题
: ids的长度是200,db.Users有差不多150k条记录

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。