1

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)

                        };

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What about adding orderby g.Sum(n => n.Amount) between group and select?
@Aducci generated SQL will contain two Sum(Amount) columns in that case - one for ordering, and one for result. (according to LinqPad)
@user1178740 what donts work means? Exception? If you want to have items with biggest sum, you need to do OrderByDescending instead of OrderBy (same relates to you SQL)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.