user1178740
user1178740

Reputation: 23

how convert sql to linq

How do I do this

Select top 10 Foo from MyTable

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

in 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)

                        };

Upvotes: 1

Views: 106

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

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):

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.

Upvotes: 1

Raphaël Althaus
Raphaël Althaus

Reputation: 60503

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

Upvotes: 1

Related Questions