Viks
Viks

Reputation: 413

Grouping data with sum

I have the following list:

 mat.Add(new Material() { ID = 1, ProdName = "Cylinder", Weight=23, Discontinued='N'  });
 mat.Add(new Material() { ID = 2, ProdName = "Gas", Weight = 25, Discontinued='N' });
mat.Add(new Material() { ID = 3, ProdName = "Match", Weight = 23, Discontinued='N' });

I want a result as:

2 Products have Weight 23 and Discontinued N
1 Product have Weigth 25 Discontinued N

Upvotes: 0

Views: 206

Answers (3)

Viks
Viks

Reputation: 413

Got it!

.GroupBy(re => new { re.Weight, re.Discontinued })
           .Select(grp => new { CXXX = group.Key, Count = grp.Count()

Upvotes: 0

SKG
SKG

Reputation:

"just" group by Weight and Discontinued.

something like : var result = mat.GroupBy(a=>new{a.Weight,a.Discontinued}).Select(b=>new b.Key.Weight,b.Key.Discontinued,Count = b.Count()});

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504052

It's not clear exactly what you're actually grouping by - is it both weight and the discontinued status? If so, you can just do:

var query = mat.GroupBy(material => 
                        new { material.Weight, material.Discontinued });

foreach (var result in query)
{
    Console.WriteLine("{0} products have {1}", result.Count(), result.Key);
}

Upvotes: 1

Related Questions