brianc
brianc

Reputation: 475

How to group C# class object values. Is this possible with LINQ?

I have been experimenting with grouping object fields and can't seem to get this working.

Here is the class object

  public class Inventory
    {
        public string warehouse_id { get; set; }
        public string product_id { get; set; }
        public int quantity { get; set; }
    }


     public List<Inventory> inventories { get; set; }

The data is coming in via JSON from an API call as such:

{
"inventories": [{
    "warehouse_id": "warehouse1",
    "product_id": "productA",
    "quantity": 5400
}, {
    "warehouse_id": "warehouse2",
    "product_id": "productA",
    "quantity": 571
}, {
    "warehouse_id": "warehouse3",
    "product_id": "productA",
    "quantity": 0
}, {
    "warehouse_id": "warehouse1",
    "product_id": "prod_B",
    "quantity": 0
}, {
    "warehouse_id": "warehouse2",
    "product_id": "prod_B",
    "quantity": 0
}, {
    "warehouse_id": "warehouse3",
    "product_id": "prod_B",
    "quantity": 1
}, 

] }

No problems deserializing the object.

Request request = new Request("api/path/to/get/inventory/data", Method.GET);
var r= request.Execute<InventoryReport>();

Now I have a populated InventoryReport object.

What I need is to ignore the warehouse_id value and group the quantity data by product.
EX. "inventories": [{ "warehouse_id":"any value here", "product_id": "productA", "quantity": 5571 // Here we have grouped the total quantity by product },

The question is in two parts. Is it possible to get this result with LINQ? I tried this but it does not work (I am thinking because of the variable warehouse_ids.)

 var groupedInventory = from newObject1 in r.inventories
            group arrayObject1 by new { newObject1.quantity, newObject1.product_id }
            into g
            select new { KKey = g.Key, Obj = g };

If not possible, what is the best way to approach this. I'm just not getting it so any guidance would be helpful.

Upvotes: 2

Views: 52

Answers (1)

Nico Schertler
Nico Schertler

Reputation: 32627

Try this

var groupedInventory = from obj in r.inventories
                       group obj by obj.product_id into g
                       select new Inventory() { product_id = g.Key, quantity = g.Sum(e => e.quantity) };

I think it is pretty self-explanatory. If you have questions, leave a comment.

Upvotes: 4

Related Questions