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

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();

Related

How do I output a simple count (int) from a LINQ query?

I want to obtain the distinct count of a column in my data table.
I have the following so far
public int DocumentsProcessed()
{
var query = from data in this._data
let docID = data.Field<string>("Document ID")
select new
{
docID
};
var query2 = from d in query
select d.docID.Distinct().Count();
var result = query2;
return result;
}
where this._data is
private IEnumerable<DataRow> _data;
But the result is an IEnumerable. I'm looking for just a single integer as an answer.
EDIT: I tried grouping the data first by Document ID column and then counting the groups, but it gave me the wrong number - for example I have 16 rows where all the Document ID are the same, so the Distinct count should be 1 but I was getting 16.
So in your example for every row you're doing a select distinct. I believe what you want is:
var query = from data in this._data
let docID = data.Field<string>("Document ID")
select new
{
docID
};
var distinctCount = query.Distinct().Count();
I suppose that data is DataTable object so try it in this manner
int count = _data.
.AsEnumerable()
.Select(r => r.Field<string>("Document ID"))
.Distinct()
.Count();

Grouping on virtual (predefined) column in linq

I am trying to write a linq query for one of my dashboard which retrieves data based on some conditions. I want to display records count based on the different status available in my table.
Following is the SQL query in which I am trying to convert into Linq.
select count(id) cnt, 'Available' label from table where date = sysdate
Above query is returning below result in DB IDE. This is the result I want with linq
cnt label
0 Available
I've tried with following linq query but it is returning 0 count and hence result is not being retrieved.
var data = (from a in context
where a.date = System.DateTime.Now
group a in a.id into g
select new {
cnt = g.Count(),
label = 'Available'
}).ToList();
How do I achieve above mentioned result in linq. Your help will be appreciated.
Thanks
-------------EDIT----------------
Updated LINQ query
var data = (from a in context.TableA
where a.id = uniqueID
group a in a.id into g
select new {
cnt = g.Count(),
label = 'Available'
}).Concat(from a in context.TableB
where a.id = uniqueID
group a in a.id into g
select new {
cnt = g.Count(),
label = 'WIP'
}).ToList();
To count the number of elements matching a predicate in a linq query simply use the where clause:
var results =
from a in context
where a.date.Date == DateTime.Now.Date
&& a.id == someIdHere
select a;
var data = new {
count = results.Count(),
label = "Available"
};
Or, in extension method syntax (which I prefer):
var results = context.Where(a => a.date.Date == DateTime.Now.Date && a.id == someIdHere);
var data = new {
count = results.Count(),
label = "Available"
};
Also be careful when comparing a DateTime object with regards to what results you desire; comparing DateTime.Now to a date will likley return false since it will compare the time code as well, use the DateTime.Date property to obtain only the date from the object for the purposes of comparison.

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.

LINQ with Group By and Having Clause with Min(string)

There are examples with group by - having count or select minimum date with linq on the web but I couldn't find a particular solution for my question. And also I don't have an advanced linq understanding to combine these solutions that I found so far.
I have a SQL query like this:
select client_id
from my_table /* Column1 : client_id, Column2 : _month */
group by client_id
having min(_month) = '2009-11'
My question is: How can I convert this query into c# linq?.
So far I wrote something like this but it doesn't give what I have to have:
var query = dataTable.AsEnumerable() // This is my_table
.GroupBy(c => c.Field<Int32>("client_id"))
.Select(g => new
{
g.Key,
minMonth = g.Min(c => c.Field<string>("_month"))
})
.Where(d => d.minMonth == "Some String like '2009-11'");
It actually gives me the result of this SQL which I don't need:
select client_id, min(_month)
from my_table
where _month = '2009-11'
group by client_id
Note: _month is a string which is formatted like YYYY-MM.
Try this:
var results = mytable.GroupBy(x => x.client_id)
.Where(x => x.Min(y => DateTime.ParseExact(y._month,"yyyy-MM",null))
== new DateTime(2009,11,1))
.Select(x=>x.Key);
The having clause is implemented within the Where in this LINQ statement. After grouping by client_id, we use x.Min to implement the min aggregate function on _month, and then use the ParseExact method to parse as a year-month combination to do the comparison.
From the SQLFiddle provided by OP, there are 4 records returned. A demo using identical data and the above query also returns the same 4 records.

Sum database column entries in 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);

Categories