LINQ - How to sum all columns of filtered dataset

Viewed 111

I have a dataset that contains a stock list and i am trying to return the quantity of a user selected item.

Lets say this is the DB structure:

ItemName    Quantity    CheckedOut

MiniPC      4           False
MiniPC      1           False

To do this I am trying to useLINQ, however, so far I can either only return how many times the item of a specific name is listed in the database, or the first quantity field.

The first query is:

 var itemQtyInStock = from myRow in stockdTc.AsEnumerable()
                                         where (myRow.Field<string>("ItemName").ToUpper() == itemNameToSearch) && (myRow.Field<bool>("CheckedOut") == false)
                                         select myRow;

This returns: 2

the second query is:

var itemQtyInStockTotal = Convert.ToInt32(from myRow in stockdTc.AsEnumerable()
                                                              where (myRow.Field<string>("ItemName").ToUpper() == itemNameToSearch) && (myRow.Field<bool>("CheckedOut") == false)
                                                              select myRow.Field<string>("Quantity"));

This returns: 4

Both query’s are wrong as it should return: 5

How can i sum up all the quantity fields?

EDIT:

This is the answer for anyone wanting it:

 var itemQtyInStockTotal = stockdTc.AsEnumerable().Where(myRow => (myRow.Field<string>("ItemName").ToUpper() == itemNameToSearch) && (myRow.Field<bool>("CheckedOut") == false)).Sum(myRow => Convert.ToInt32((string)myRow["Quantity"]));
1 Answers

You could do:

var sum = stockTc
    .AsEnumerable()
    .Where(x=> // your filters)
    .Sum(x => (int) x["Quantity"]);
Related