简体   繁体   中英

Aggregate List Based on Child Properties

I have an class structure representing an item's list of materials, with each material having a list of additional properties. Similar to the following:

  • MaterialList
    • MaterialPiece
      • AdditionalPropertyList
        • AdditionalProperties

Each class has a ChildPieces list property containing the list of items in the next level; for example, the MaterialList class has

public List<MaterialPiece> ChildPieces {get;set;}

So an example instance of this might be

  • WheelSet
    • Wheel
      • Wheel Properties
        • Quantity: 1
        • Partnumber: R1000
    • Wheel
      • Wheel Properties
        • Quantity: 1
        • Partnumber: R1000

What I want to do is aggregate the MaterialList to group together the MaterialPiece objects based on some of their properties - the Partnumber in the above example.

This would result in

  • WheelSet
    • Wheel
      • Wheel Properties
        • Quantity: 2
        • Partnumber: R1000

I want to do this in the outermost object, ie I want to implement

class MaterialList : BasePiece
{
    public void AggregateMaterialPieces()
    {
        var newList = ChildPieces.Where(...)
    }
}

So my question: Can I use LINQ to group and sum the MaterialPieces in the MaterialList based on some known values in the AdditionalPropertyList?

Your question isn't quite specific enough but anyway, here's some code that will give you the quantities for each partnumber.

 var groupings = list.SelectMany(x => x.AdditionalPropertyList).GroupBy(x => x.PartNumber).Select(g => new { PartNumber=g.Key, Quantity=g.Sum(x => x.Quantity) } );

 foreach (var g in groupings)
    Console.WriteLine("PartNumer: {0} Total: {1}", g.PartNumber, g.Quantity);

I'm not positive this is correct, if it doesn't work let me know and I'll try to make time to actually test it. The basic idea is to flatten the list to all the additional properties, then you group those by partnumber, then for each of the groupings you create a new anonymous object which uses the partnumber (the group key) and calls aggregate on the list of groupings to get the sum of all the quantities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM