sum of item prices that have the same item id - c#

I want sum of all item prices in all rows in the database table that have the same item id. I mean the result should be one number and put it on textbox automatically when I choose a specific item id from dropdownlist
How can I do it in linq?
public double oIlstGetVouchersDetailjh(int nvoucherID)
{
Training_sNairoukhEntities1 sNairoukhEntities1 = new Training_sNairoukhEntities1();
double sum = (from Entity in sNairoukhEntities1.INV_InventoryItems
where Entity.ItemID == nvoucherID
select Entity.ItemPrice).sum();
return sum;
}
or
public double oIlstGetVouchersDetailjh(int nvoucherID)
{
Training_sNairoukhEntities1 sNairoukhEntities1 = new Training_sNairoukhEntities1();
double olstInvoicesSrech = from Entity in sNairoukhEntities1.INV_InventoryItems
group Entity by Entity.ItemID == nvoucherID into g
select g.sum(Entity => Entity.ItemPrice);
return olstInvoicesSrech;
}
but the second query give me this msg Cannot implicitly convert type 'System.Linq.IQueryable' to 'double

In your case, this will work:
Training_sNairoukhEntities1 sNairoukhEntities1 = new Training_sNairoukhEntities1();
double sum = (from Entity in sNairoukhEntities1.INV_InventoryItems
where Entity.ItemID == nvoucherID
select Entity.ItemPrice).Sum(); // Change sum to Sum
return sum;
Here's a simpler way:
sNairoukhEntities1.INV_InventoryItems.Where(item => item.ItemID == nvoucherID).Sum(item => item.ItemPrice);

Related

How to make a Sum of values in a list for Charts? [ SOLVED ]

I'm currently working on an MVC.NET application and I need help for one thing.
I need to get some data from my database to draw charts.
All is good but I need to make a sum of valor in the list but I don't know how to do that.
At the moment, I can only get the number of entries for the Fuel Value and I know that it comes from repartitions.Add(list.Count *)
So my Question is : How can I do the sum of the valor of the list , instead of the count?
public ActionResult Conso()
{
var veh = from s in db.Fuel
select s;
var list = veh.ToList();
List<int> repartitions = new List<int>();
var comp = list.Select(x => x.VehicleId).Distinct();
foreach (var item in comp)
{
repartitions.Add(list.Count(x => x.VehicleId == item));
}
var rep = repartitions;
ViewBag.COMP = comp;
ViewBag.REP = repartitions.ToList();
return View();
}
If you want the count of filtered records then you can use Count() method:
repartitions.Add(list.where(x => x.VehicleId == item).Count());
for SUM:
repartitions.Add(list.where(x => x.VehicleId == item).Sum(x => x.columnName));

How do I drill down to specific data in my LINQ query result?

I want to drill down into a particular item in my data and output the list of results to the output window. My query result looks like this
private IEnumerable<DataRow> _data;
var query = from data in this._data
group data by data.Field<string>("Form Name") into groups //same as Form ID
select new
{
formName = groups.Key,
items = from d in groups
group d by d.Field<string>("Item Name") into grps
let name = grps.Key
let documentIDGroups = grps.GroupBy(t => t.Field<string>("Document ID"))
let documentIDGroupsCount = documentIDGroups.Count()
let distinctDocumentValueCount = from data in documentIDGroups
select new
{
docID = data.Key,
distinctDocValueCount = data.Where(t => string.IsNullOrEmpty(t.Field<string>("Document Value").Trim()) == false).Select(t => t.Field<string>("Document Value")).Distinct().Count()
}
let sum = distinctDocumentValueCount.Sum(t => t.distinctDocValueCount)
let distinctItemsNames = from data in grps
select data.Field<string>("Item Name").Distinct().Count()
let count = distinctItemsNames.Count()
select new
{
itemName = name,
documentIDGroups,
documentIDGroupsCount,
averageChoices = Math.Round(((decimal)sum / documentIDGroupsCount), 2),
distinctDocumentValueCount,
sum
}
};
So on that query result I want to drill down into a particular form name, and from there get a particular Item Name and so on
so the first step is to get the grouping of items and I have
var items = from d in query where d.formName == "someName" select d.items;
but I don't know how to isolate the items by a particular string.
I want to do the following
var item = from d in items where d.itemName == "anItemName" select d;
But I don't know the syntax.
Use the .FirstOrDefault extension if you expect a single item to be returned from your query. SO:
var item = (from d in items where d.itemName == "anItemName" select d).FirstOrDefault();

Subtracting quantity using Entity Model

I am trying to subtract the field "QtyOnHand" in the table "Inventory" from the quantity in List. But I get this error:
Unable to cast object of type 'System.Collections.Generic.List`1[System.Int32]' to type 'System.IConvertible'.
It shows that the error occurs at:
var cartQty = (from i in items where i.ProductId == Convert.ToInt32(productId) select i.Qty).SingleOrDefault();
My code is the following:
protected void btnCheckout_Click(object sender, EventArgs e)
{
int inventoryQty;
List<Item> items = Session["Cart"] as List<Item>;
using (ProjectEntities myEntities = new ProjectEntities())
{
var productId = (from i in items select i.ProductId).ToList();
var cartQty = (from i in items where i.ProductId == Convert.ToInt32(productId) select i.Qty).SingleOrDefault();
var inventory = (from q in myEntities.Inventories
where q.ProductId == Convert.ToInt32(productId)
select q).SingleOrDefault();
inventoryQty = inventory.QtyOnHand - cartQty;
myEntities.SaveChanges();
Response.Redirect("~/Home.aspx");
}
}
Thanks in advance!
var productId = (from i in items select i.ProductId).ToList();
productId variable contains a list of items and you are trying to pass that to Convert.ToInt32 to method which is not expecting a collection of items!. That is causing the issue.
Since you are cart may have more than one item, you probably need to loop throug the productIds and do your other calculation.
var productIdList = (from i in items select i.ProductId).ToList();
foreach(var productId in productIdList)
{
var cartQty = (from i in items where i.ProductId == Convert.ToInt32(productId)
select i.Qty).SingleOrDefault();
// Your remaining code
}
I am assuming the productId in your cart item is of numeric value, but of string type. Then only the Convert.ToInt32 will work as it is expecting the string representation of some valid numeric value (Ex :"234")
If it is of int type, you do not need the Convert.ToInt32(productId) part in your where clause, just use i.ProductId==productId

Get multiple MAX values from single query across multiple columns using Linq

I'm trying to select the max values of 3 columns from a table. All the fields being returned from the query are Strings.
What I have sofar
var step1 = from result in t_hsbc_staging_trts_derived_tbl_ac_balance.AsQueryable()
where result.branch_no == brnchnu
&& result.deal_id == dealid
&& result.group_mbr == grpmem
&& result.ac_type != "RMC"
select result ;
var branch = from result in step1
select new {ccbranch = result.cc_branch.Max()};
var sect = from result in step1
select new { ccsect = result.cc_sect.Max()};
var dept = from result in step1
select new { ccdept = result.cc_dept.Max()};
foreach (var result in branch)
{
string cc_branch = result.ccbranch.ToString();
}
The error I'm getting at the foreach statement is:
Sequence operators not supported for type 'System.String'.
There must be an easier way to just get the max values from this table?
You are calling the Max() function on result.cc_branch which is itself a string. Even if it was successful, it would return the character of the string that has the largest unicode number, i.e.
string s = "one-two-three";
Console.WriteLine(s.Max()); // returns 'w'
Since I assume that is not what you want, and that you want the largest branch / section / department value, you can use:
string branch = (from result in step1 select result.cc_branch).Max();
string sect = (from result in step1 select result.cc_sect).Max();
string dept = (from result in step1 select result.cc_dept).Max();

LINQ: Efficient way to get sum of all child items

I have the following for each loop to get sum of all child objects. Is there a better way using LINQ?
Purchase p1 = db.Purchases.FirstOrDefault(p => p.PurchaseId == 1);
int total = 0;
foreach (SellingItem item in p1.SellingItems)
{
total = total + Convert.ToInt32(item.Price);
}
REFERENCE:
How to get the sum of the volume of highest and lowest priced items in linq
Using the ALL operator in linq to filter child items of EntitySet
Sounds like you just want:
// Any reason for FirstOrDefault rather than SingleOrDefault?
var purchase = db.Purchases.FirstOrDefault(p => p.PurchaseId == 1);
if (purchase != null)
{
var total = purchase.SellingItems
.Sum(x => Convert.ToInt32(x.Price));
...
}
// TODO: Work out what to do if there aren't any such purchases
Why do you need the conversion of the price though? What type is Price, and why isn't it already the right type? (And does that really want to be int rather than decimal?)
p1.SellingItems.Sum(p => p.Price)
Try using the Linq Sum method:
Purchase p1 = db.Purchases.FirstOrDefault(p => p.PurchaseId == 1);
int total = p1.SellingItems.Sum(item => Convert.ToInt32(item.Price));
It is not more efficient, in that it will not be any faster. But it is more concise.

Categories