【问题标题】:different results between Linq and SQLLinq 和 SQL 的结果不同
【发布时间】:2013-09-25 01:04:18
【问题描述】:

我不知道为什么我在这个 SQL 和 LINQ 之间得到不同的结果 你能告诉我为什么...?

SQL:

select distinct top 50 (id) as d_id
from talbe1
where id<>-1
order by d_id  asc;

林克:

    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() );
    }

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

.......

【问题讨论】:

    标签: c# mysql .net linq


    【解决方案1】:

    这是 LINQ to 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();
    

    【讨论】:

    • 该死,我错过了很多 this :P 快速编辑虽然...应该是.OrderBy(t =&gt; t),因为那时它是一个IEnumerable&lt;int&gt;
    • 这就是为什么我错过了第一个答案...我打字慢:P
    • @Corey - :-) 那就不要在你的手机上回答问题,几周前我试过了,在我能打字之前,三个人已经提交了答案。哈哈
    【解决方案2】:

    问题在于Distinct() 方法的工作方式。不幸的是,它可以(并且通常会)更改列表中项目的顺序。您需要在调用Distinct()之后订购列表。

    试试这个:

    IList<int> myResults =
        (
            from t in dbconn.table1
            where t.id != -1
            select t.id
        ).Distinct().OrderBy(i => i).Take(50).ToList();
    

    【讨论】:

      【解决方案3】:

      试试

      var myResults = dbconn.Table1.Where(e => e.id != -1).Select(e => e.id).Distinct()
               .OrderBy(t => t).Take(50).ToList();
      

      【讨论】:

      • 1.不工作。 2. 不返回IList&lt;int&gt;。 3. 没有解释为什么
      • 抱歉,已经修复了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多