[英]different results between Linq and SQL
i don't know why i get different results between this SQL and LINQ Could you like to tell me why...? 我不知道为什么我在此SQL和LINQ之间会得到不同的结果。您能告诉我为什么吗?
SQL: SQL:
select distinct top 50 (id) as d_id
from talbe1
where id<>-1
order by d_id asc;
Linq: LINQ:
IList<int> myResults =
(from t in dbconn.table1
where t.id != -1
orderby t.id ascending
select t.id
).Distinct().Take(50).ToList();
int callCnt = 0;
foreach (int row in myResults)
{
callCnt++;
Console.WriteLine(callCnt.ToString() + " " + row.ToString() );
}
The SQL get the results i want, but the Linq result is like : SQL得到我想要的结果,但是Linq结果像:
1 72662
2 84945
3 264577
4 77655
5 71756
6 76899
7 76719
8 77669
9 152211
10 79168
11 72334
12 71399
13 246031
14 80748
15 77715
.......
This is a limitation of LINQ to SQL, where the OrderBy()
must occur after the Distinct()
, try this: 这是LINQ对SQL的限制,其中
OrderBy()
必须在Distinct()
之后发生,请尝试以下操作:
IList<int> myResults =
(from t in dbconn.table1
where t.id != -1
select t.id
).Distinct().OrderBy(t => t).Take(50).ToList();
The problem is the way that the Distinct()
method works. 问题是
Distinct()
方法的工作方式。 Unfortunately it can (and usually does) change the order of the items in the list. 不幸的是,它可以(并且通常确实)更改列表中项目的顺序。 You need to order the list after calling
Distinct()
. 您需要在调用
Distinct()
之后对列表进行排序。
Try this: 尝试这个:
IList<int> myResults =
(
from t in dbconn.table1
where t.id != -1
select t.id
).Distinct().OrderBy(i => i).Take(50).ToList();
Try 尝试
var myResults = dbconn.Table1.Where(e => e.id != -1).Select(e => e.id).Distinct()
.OrderBy(t => t).Take(50).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.