将SQL语句转换为Linq?

时间:2013-07-01 16:14:53

标签: c# linq

我有一个名为Outweigh的表,它有大约50个字段。我需要创建一个Linq查询,就像这个SQL查询一样。

SELECT DISTINCT Product, 
   Medication, 
   SUM(NettWeight) as NettWt, 
   COUNT(DISTINCT CustCode) as Customer, 
   COUNT(DISTINCT DktNo)as DktNo
FROM outweigh
GROUP BY Product, Medication
ORDER BY Product, Medication

结果如下:

enter image description here

我写了一些代码如下,效率不高。

lstOutWeigh = dbContext.Outweighs
                       .Where(o => o.DateOut >= StartDate && o.DateOut <= EndDate)
                       .ToList();

  var k = from t in lstOutWeigh select new {t.Product,t.Medication,t.NettWeight};
  var l  = from t in k
           group t by new { t.Product, t.Medication } into g
           select new someclass
           {
               prod =g.Key.Product,
               med = g.Key.Medication,
               tonnes = (double) g.Sum(x => x.NettWeight),
               count = g.Count()
           };

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

正如有人提到的,http://sqltolinq.com/效果很好。

http://www.linqpad.net/也是另一个很棒的工具(我/我个人在工作的地方使用),可以帮助你在这些类型的语句之间进行转换 - 即使你喜欢使用Lambda表达式 - 我认为使用LINQ查询的最简单方法之一。

答案 1 :(得分:1)

类似的东西,

db.Outweighs.GroupBy(ow => new { ow.Product, ow.Medication })
    .OrderBy(g => g.Key)
    .Select(g => new
        {
            g.Key.Product,
            g.Key.Medication,
            NettWt = g.Sum(ow => ow.NettWeight),
            Customer = g.Select(ow => ow.CustCode).Distinct().Count(),
            DktNo = g.Select(ow => ow.DktNo).Distinct().Count()
        })

等同于您在问题中提供的SQL。但是,你提出的Linq-To-Sql并不匹配。

答案 2 :(得分:0)

     var t = (from  p in Context.outweigh
              group p by new {p.Product,p.Medication}  into g
              select new {Product= t.Product,Medication=t.Medication, NettWt = g.Sum(x => x.NettWeight),Customer=g.Count())
             .Distinct().orderby(new {p.Product, p.Medication});