Sum database column entries in c# - c#

I am new to SQL and databases. I have a table in SQL Server. In that table there is a column price. I want to sum all the price. What I tried is :
var totalAmount = db.Orders.Select(p => new { sum += p.Price });
What I am doing wrong here ?

You could try doing a .Sum like below:
var totalAmount = db.Orders.Select(p => p.Price ?? 0).Sum();
Similiar question at sum column with linq to sql

var totalAmount = db.Orders.Sum(p => p.Price);

you should be using SUM (LiNQ Extension Method)
int total = db.Orders.Sum(p => p.Price);

Related

Converting SQL query into Linq which used complex sum with group by

Here is my Service table's columns:
id
serverPlace
count
Here is a SQL query which I need to convert it into Linq:
SELECT Service.id,
Service.serverPlace,
sum(Service.count * 12 + MONTH(getdate())) AS sum
FROM Service
GROUP BY Service.id, Service.serverPlace;
I do not know how to convert and implement sum section with Linq.
It should look like this :
var month = DateTime.Now.Month;
var result = await dbContext.Services.GroupBy(r=> new { r.Id, r.ServerPlace })
.Select(r=> new {
r.Key.Id,
r.Key.ServerPlace,
Sum = r.Sum(q=> q.Count*12 + month)
}).ToArrayAsync();

Filtering datatable where sum of grouped column value is not zero

Can we display the data table rows where grouped column value is not zero.
first, I need to group by sno and display ungrouped data where amount is not zero.
For example:
I have a data table like below:
need output like this
However I get this with the below code
FinalDataTable = table.AsEnumerable()
.GroupBy(r => new { Col1 = r["sno"]})
.Select(g =>{
var row = table.NewRow();
row["sno"] = g.Key.Col1;
row["amount"] = g.Sum(r => r.Field<decimal>("amount"));
return row;
}).CopyToDataTable();
Yes, what you want to do is Group by sno and then use Where to find those records where the Sum of amount is not zero. Then simply use Select Many to unwrap those groups back into rows.
I think this should do it (I've assumed amount is an int)
FinalDataTable = table.AsEnumerable()
.GroupBy(r => r["sno"])
.Where(g => g.Sum(r => (int)r["amount"]) != 0)
.SelectMany(r => r)
.CopyToDataTable();
Here is a live example: https://dotnetfiddle.net/ixi0aW

Very slow performance on LINQ subquery

I am facing a performance issue when doing a LINQ subquery in C#.
The query is as follows:
var _result = _db.Prices
.Join(_db.Vendors,
e => e.VendorId,
v => v.VendorId,
(e, v) => new {
TotalPrice = e.TotalPrice,
Vendor = v.Title,
AmountPaid = _db.Amounts
.Where(p => p.PrId == e.PrId )
.GroupBy(p => p.PrId )
.Select(grp => (decimal?)grp.Sum(k => k.AmountPaid) ?? 0M)
.FirstOrDefault()
});
Prices, Vendors and Amounts are Entity Framework objects.
Firstly I am doing a join of Prices to Vendors table on VendorId and on the result I am adding a calculated field AmountPaid. The result is a subquery which returns the sum of AmountPaid column in Amounts table for the given record matched by PrId index.
All the above is returned as a JSON object in ASP.NET web api.
The result of the above for the records in a database is only 1992 rows.
The above command neeeds about 20 seconds to return the result. If I remove the AmountPaid calculation it needs only 1 second.
If I run the equivalent SQL command in SQL Server studio it needs only half a second with the AmountPaid calculation included:
SELECT Prices.*, Vendors.Title,
AmountPaid = (SELECT SUM(AmountPaid) from Amounts where Amounts.PrId = Prices.PrId GROUP BY PrId) FROM Amounts
INNER JOIN Vendors ON Amounts.VendorId = Vendors.VendorId
Is there a way to fix this?
I cannot understand the issue since the SQL command does not have an issue in execution.
Is there an error on the LINQ syntax, or another way to get in LINQ the same result set?

Find Sum of product of 2 columns in LINQ

Find sum of product of 2 columns in LINQ
I have a list of educationprogram objects with 2 properties NOOfPerson & Hours.
I want a sum of product of 2 properties
SUM[NOOfPersons*Hours]
How can I write a LINQ query for this?
List<educationprogram> edu = (from e in dbContext.educationprograms
where e.YearId == 2015
select e).ToList();
This returns the list of object I have to use. But how can I return SUM[Col1*Col2]?
If the two columns are under the educationprograms table then:
var sum = dbContext.educationprograms.Sum(ep => ep.NoOfPeople * ep.Hours);
you can also add a Where clause:
var sum2 = dbContext.educationprograms.Where(e => e.Year == 2015).Sum(ep => ep.NoOfPeople * ep.Hours);
var edu= from e in dbContext.educationprograms
where e.YearId == 2015
select new
{
sum = e.NoofPersons*e.Hours
}).ToList();
now edu is the list of products of noofperson column and hours column.

How can i calculate sum of this linq to sql query?

I'm beginner in linq to sql, I using the c# linq to sql and wrote this query:
var query_find = (from t in behzad.Interconnect_Traffic_Analysis_Details
where t.FILEID == FILE_ID && t.code_operator.Trim() == item.code_operator.Trim()
select new { t.moddat }).ToList();
I want to calculate sum of the t.moddat column, how can I convert this query to sum the values? Thanks.
t.moddat is a nvarchar(max) datatype and save into that double datatype value.
Try this
var query_find = (from t in behzad.Interconnect_Traffic_Analysis_Details
where t.FILEID == FILE_ID && t.code_operator.Trim() == item.code_operator.Trim()
select new
{
sum= t.moddat
}).ToList();
var sum= query_find.Sum(x => Convert.ToDouble(x.sum));

Categories