0

我有一个名为 Outweigh 的表,其中包含大约 50 个字段。我需要创建一个类似于此 SQL 查询的 Linq 查询。

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

结果如下:

在此处输入图像描述

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

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

有什么建议么?

4

3 回答 3

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 不匹配。

于 2013-07-01T16:38:50.007 回答
1

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

http://www.linqpad.net/也是另一个很棒的工具(我/我们个人在我工作的地方使用),它可以帮助您在这些类型的语句之间进行转换 - 如果您愿意,甚至可以使用 Lambda 表达式 - 在我的意见是使用 LINQ 进行查询的最简单方法之一。

于 2013-07-01T16:24:05.183 回答
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});
于 2013-07-01T16:33:58.503 回答