为什么“.Distinct()”无法按预期工作

时间:2012-11-23 06:40:18

标签: c#

  

可能重复:
  DISTINCT() and ORDERBY issue

listOrders.DataSource = (from sp in dbdata.Specifications.Where(i => i.Approve == "Yes" && i.Awailable_BOM == "Yes")
                                     join ord in dbdata.Orders on sp.O_id equals ord.O_id
                                     join prd in dbdata.Products.Where(k => k.Hours_prd == null) on ord.O_id equals prd.O_ID
                                     orderby ord.Special, sp.Due_date
                                     select ord.O_id).Distinct();

我想通过“ord.Special,sp.Due_date”进行排序,但是在我放入“Distinct();”后它不起作用。那么如何通过“ord.Special,sp.Due_date”订购并获得不同的值。

1 个答案:

答案 0 :(得分:0)

我认为这会返回有序的ID:

listOrders.DataSource = 
   from sp in dbdata.Specifications.Where(i => i.Approve == "Yes" && i.Awailable_BOM == "Yes")
   join ord in dbdata.Orders on sp.O_id equals ord.O_id
   join prd in dbdata.Products.Where(k => k.Hours_prd == null) on ord.O_id equals prd.O_ID
   select new { ord.Special, sp.Due_date, ord.O_id } into x
   group x by x.O_id into g
   select new { g.Key, X = g.OrderBy(i => i.Special).ThenBy(i => i.Due_date).First()) } into y
   orderby y.X.Special, y.X.Due_date
   select y.Key;

评论:

  • 仅选择您感兴趣的字段到x
  • 按字段将这些字段分组到您要分组的字段g
  • 从每个组中选择密钥(ord.O_id)和组项X,这将定义结果中id的顺序(在这种情况下,将返回First id的出现)
  • X
  • 订购结果
  • 选择Keyord.O_id