1

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)

Chris Fazzio
  • 375
  • 1
  • 6
  • 16

1 Answers1

4
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))
                });
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • I will test it, but I am unsure if this will allow for a certain instance.. Example if there are 3 Layers, but the item only has 2 layers to it.. will it have (Layer1Value, 0, Layer3Value) for example.. anyway gonna test – Chris Fazzio Jun 11 '13 at 16:21
  • 1
    @ChrisFazzio no it will have `Layer1Value`, `Layer3Value`. If that's not what you want, you should mention this. – Raphaël Althaus Jun 11 '13 at 16:23
  • My fault for lack of information.. This is my real problem though.. To get the values in this order.. See the explanation at the bottom of my post that I added.. – Chris Fazzio Jun 11 '13 at 16:35