【问题标题】:Order By in Linq to Entities在 Linq to Entity 中排序
【发布时间】:2017-01-29 11:31:16
【问题描述】:

我有两列 sizename 和 orderof 的 sql 表。我想从该表中选择所有大小名称,但使用 EF6 和 Linq to Entities 的 orderof 升序排列

我曾经使用过这样的查询。但它不起作用(排序)

   var sizedetails = (from size in enty.StyleSizes
                               where size.OurStyleID == ourstyleid
                               orderby size.Orderof
                               select new
                               {
                                   size.SizeName

                               }).Distinct();


            //var sizedetails = enty .StyleSizes.Where(u => u.OurStyleID == ourstyleid).Select(u => u.SizeName ).Distinct();

            foreach (var sizedet in sizedetails)
            {
                dt.Columns.Add(sizedet.SizeName.Trim(), typeof(String));
            }

我知道这可能已经被问过了。但是这些问题中提供的解决方案都不适合我

【问题讨论】:

  • 你试过order by after select???
  • 嗨,我试图在内存类集合中回答它,请检查并让我知道这是否会返回正确的结果
  • 最后使用orderby。就是说,看起来您正在按您没有选择的东西(Orderof)订购,然后采用不同的集合(SizeName)。这不是 SQL 可以轻松表达的。
  • @ta.speot.is 我必须做 Distinct 否则我可能会以多个 sizenames 结束。

标签: entity-framework linq c#-4.0 entity-framework-6


【解决方案1】:

由于 LINQ to Entities 将您的查询转换为 SQL,因此在 Distinct 之前排序没有任何效果。问题是在Distinct 之后,您无法访问订购所需的属性。

所以您需要另一种方法,幸运的是 GroupBy 方法 - 它类似于 Distinct 但允许您访问共享相同键的元素的属性。因此,您可以根据一些聚合对结果进行排序(在您的情况下,Min 是合适的):

var sizedetails = from size in enty.StyleSizes
                  where size.OurStyleID == ourstyleid
                  group size by size.SizeName into sizeGroup
                  orderby sizeGroup.Min(size => size.Orderof)
                  select new
                  {
                      SizeName = sizeGroup.Key
                  };

【讨论】:

  • @SreenathGanga 谢谢,实际上我只是忘了删除( :)
【解决方案2】:
I dint tried with DB but with in memory collection it gives be correct result  .

这是我的课。

class StyleSizes
    {
        public int Orderof { get; set; }
        public string SizeName { get; set; }
         public int OurStyleID { get; set; }
    }
     // logic to ue orderby 
        var list = new List<StyleSizes> {  new StyleSizes { Orderof=2,SizeName="B",OurStyleID=1 },
      new StyleSizes { Orderof=11,SizeName="C" ,OurStyleID=2},
       new StyleSizes { Orderof=9,SizeName="D" ,OurStyleID=1},
       new StyleSizes { Orderof=9,SizeName="D" ,OurStyleID=1},
       new StyleSizes { Orderof=3,SizeName="E" ,OurStyleID=1},
       new StyleSizes { Orderof=4,SizeName="F" ,OurStyleID=1}

    };

    var orderList = list.Where(x=>x.OurStyleID==1).OrderBy(x => x.Orderof).Select(c => new { c.SizeName }).Distinct();

【讨论】:

  • 它可以工作,但是当我添加 where 条件时它会停止排序
  • 嗨@SreenathGanga 我检查了,如果你添加它也工作的地方,请查看更新的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-20
  • 1970-01-01
  • 2010-10-13
  • 1970-01-01
  • 1970-01-01
  • 2012-11-15
相关资源
最近更新 更多