Chris Fazzio
Chris Fazzio

Reputation: 375

list of sums to new list

I have a list of items with a total value in each item.. Some are in a different layer.. As shown below

**Name, Layer, Value**
Item 1, Layer1, 100
Item 1, Layer1, 200
Item 1, Layer2, 700

Now I want to combine these into a new list, and merge them together.. As shown below

**Name, List(Layer1Value, Layer2Value)**
Item 1, (300,700)

This is the code I have so far..

List<double> = 
Enumerable.Range(0, t.Select(u => u.LayerName).Distinct().Count())
.Select(idx => t.Select(a => a.sum).Sum()).ToList()

This of course is wrong and puts the totals in all the value spots.. like this

Item 1, (1000,1000)

Unsure how to get it to work correct, any help would be great.. Thanks


Added help.. Starting with a list like this

private class Items
{
    public string Name;
    public string Layer;
    public double Value;
}

List<Items> MyItems = new List<Items>();

To a list like this

private class CombinedItems
{
    public string Name;
    public List<double> LayerValues;
}

List<CombinedItems> MyCombinedItems = new List<CombinedItems>();

It should output in a specific order.. Example, If there are 4 Layers.. Layer1, Layer2, Layer3, Layer4..

And item1 has values in Layer1, and Layer 4.. then the

List needs to be as (Layer1Value, 0, 0, Layer4Value)

Upvotes: 1

Views: 110

Answers (1)

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60503

list.GroupBy(x => x.Name)
    .Select(g => new {
          Name = g.Key,
          Elements = g.GroupBy(x => x.Layer)
                      .Select(g => g.Sum(z => z.Value))
       });

Edit :

var layers = list.Select(x => x.Layer).Distinct().OrderBy(x => x);
var result = list.GroupBy(x => x.Name)
                .Select(g => new
                {
                    Name = g.Key,
                    Values = layers.Select(x =>  g.Where(n => n.Layer == x)
                                                  .Sum(z => z.Value))
                });

Upvotes: 4

Related Questions