简体   繁体   English

如何将sql转换为linq

[英]how convert sql to linq

How do I do this 我该怎么做呢

Select top 10 Foo from MyTable 从MyTable中选择排名前10的Foo

SELECT        TOP (30) Item, Descripcion, SUM(Amount) AS Suma         
FROM            Venat 
GROUP BY Item, Descripcion                          
ORDER BY Suma 

in Linq to SQL? 在Linq to SQL中?

with this only agrup by Item but not Description 仅按项目分类,而不按描述分类

var filtroprimeros30 = from nuevo in registrosVipDosAños
                     group nuevo by nuevo.Item into g         
                       select new
                        {
                            Item = g.Key,
                            Suma = g.Sum(nuevo => nuevo.Amount)

                        };

Use anonymous type for grouping: 使用匿名类型进行分组:

var filtroprimeros30 = 
     (from nuevo in registrosVipDosAños
      group nuevo by new { nuevo.Item, nuevo.Description } into g  // here    
      select new {
          g.Key.Item,
          g.Key.Description,
          Suma = g.Sum(n => n.Amount)
      })
     .OrderBy(x => x.Suma)
     .Take(30);

I'd actually go this way (because query syntax has nice syntax for grouping, but do not have ability to take N items): 我实际上会采用这种方式(因为查询语法具有很好的分组语法,但没有能力接受N个项目):

var items = from n in registrosVipDosAños
            group n by new { n.Item, n.Description } into g
            select new {
              g.Key.Item,
              g.Key.Description,
              Suma = g.Sum(x => x.Amount)
            };

var topItems = items.OrderBy(x => x.Suma).Take(30);

Query still will be executed only once, but now it's more readable. 查询仍将仅执行一次,但现在更具可读性。

syntax alternative 语法替代

var filtroprimeros30 =  registrosVipDosAnos
                        .GroupBy(m => new {m.Item, m.Description})
                        .Select(g => new {
                           Item = g.Key.Item,
                           Description = g.Key.Description,
                           Suma = g.Sum(n => n.Amount)
                        })
                        .OrderBy(x => x.Suma)
                        .Take(30);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM