Search code examples
sqlasp.net-mvcmodel

method that adds values together if ID is the same


Hello I am currently trying to figure out how to add values together if their item id's are the same in my SQL database. Here is a view of my database

Database

As you can see two of the values have the same "ItemID" with a value of 117. I want my method to return the combined quantities of the two values so in this case I would want it to return the value "14"

Here is my method inside my model that pulls the item quantity

  public int Available(Item i)
        {

            OffSiteItemDetails d = ItemDetails.Where(x => x.itemID == i.ID).FirstOrDefault();
            if (d == null)
                return 0;
            return d.qty;
        }

but just not sure how to combine the values when there is more than one value with the same ID


Solution

  • public int Available(Item i)
    {
    
        List<OffSiteItemDetails> d = ItemDetails.Where(x => x.itemID == i.ID).ToList();
        if (d == null || d.Count < 1)
            return 0;
    
        return d.Sum(x => x.qty);
    }