How write count(ColumnName) in LINQ? - linq

Hi everyone I need help write below query in LINQ
select zProcessStatus.StatusName, zProcessStatus.StatusNameDari, COUNT( ProcessProgress.SchoolID) as 'Count'
from zProcessStatus
left join ProcessProgress on ProcessProgress.ProcessStatusID=zProcessStatus.ProcessStatusID
join SubProcessStatus on zProcessStatus.ProcessStatusID=SubProcessStatus.ProcessStatusID
where SubProcessStatus.SubProcessID='18250478-7DA5-45D6-90A7-51DFE94B09C8'
group by zProcessStatus.StatusName
,zProcessStatus.StatusNameDari
I have written it as below, it's not give the expected result same as SQL query
(from zProcessStatus in _applicationContext.ZProcessStatus
join processProgress in _applicationContext.ProcessProgress on zProcessStatus.ProcessStatusId equals processProgress.ProcessStatusId into processprogressGroup
from a in processprogressGroup.DefaultIfEmpty()
join subProcessStatus in _applicationContext.SubProcessStatus on zProcessStatus.ProcessStatusId equals subProcessStatus.ProcessStatusId
where subProcessStatus.SubProcessId == subprocessid
select new
{
SchoolId = a.SchoolId.ToString(),
StatusNameDari = zProcessStatus.StatusNameDari,
StatusName = zProcessStatus.StatusName,
}).Distinct().ToList().GroupBy(x => new { x.StatusNameDari, x.StatusName, x.SchoolId }).Select(
g => new
{
g.Key.StatusNameDari,
g.Key.StatusName,
Count = g.Count()
}).ToList();

Related

Linq to SQL conversion...unable to add second COUNT

I'm trying to convert my SQL statement to a Linq statement and I'm not sure how to add the second COUNT to it. This is my SQL statement
SELECT l.Campus_Name, Labs = COUNT(*), LabsWithSubnets = COUNT(s.Lab_Space_Id)
FROM vw_Lab_Space l
LEFT JOIN vw_Subnet s on l.Lab_Space_Id = s.Lab_Space_Id
GROUP BY l.Campus_Name
ORDER BY 1
and this is my LINQ statement so far:
from l in Vw_Lab_Space
from s in Vw_Subnet
.Where(s => s.Lab_Space_Id == l.Lab_Space_Id)
.DefaultIfEmpty() // <=- triggers the LEFT JOIN
group l by new { l.Campus_Name } into g
orderby g.Key.Campus_Name
select new {
Campus_Name = g.Key.Campus_Name,
Labs = g.Count()
}
So I have everything but the LabsWithSubnets part in there. I'm just not sure how to add that in as I can't just do an s.Lab_Space_id.Count() in the select statement.
If you need table structure and sample data please see Need help creating an OUTER JOIN to count spaces.
Using your query as a basis, you need the groups to include s so you can count when non-null (I also removed the unnecessary anonymous object around the grouping key):
from l in Vw_Lab_Space
from s in Vw_Subnet
.Where(s => s.Lab_Space_Id == l.Lab_Space_Id)
.DefaultIfEmpty() // <=- triggers the LEFT JOIN
group new { l, s } by l.Campus_Name into g
orderby g.Key
select new {
Campus_Name = g.Key,
Labs = g.Count(),
LabsWithSubnets = g.Count(ls => ls.s != null)
}
However, rather than translate the SQL, I would probably take advantage of LINQ's group join to handle the query slightly differently:
var ans = from l in Vw_Lab_Space
join s in Vw_Subnet on l.Lab_Space_Id equals s.Lab_Space_Id into sj
group new { l, sj } by ls.Campus_Name into lsjg
select new {
Campus_Name = lsjg.Key,
NumLabs = lsjg.Count(),
LabsWithSubnets = lsjg.Sum(lsj => lsj.sj.Count())
};
PS Even in your query, I would use join...from...DefaultIfEmpty rather than from...from...where but depending on your database engine, may not matter.

how use multiple join in linq?

var abc1 = from dlist in db.DebtorTransactions.ToList()
join war in db.Warranties on dlist.ProductID equals war.Id
join ag in db.Agents on war.fldAgentID equals ag.pkfAgentID
join sr in db.SalesReps on war.fldSrId equals sr.pkfSrID
where dlist.TransTypeID == 1
select new
{
dlist.Amount,
dlist.TransTypeID,
name = ag.Name,
ag.pkfAgentID,
sr.pkfSrID,
salesnam = sr.Name
} into objabc
group objabc by new
{
objabc.TransTypeID,
objabc.name,
objabc.salesnam,
objabc.Amount
};
var amt1 = abc1.Sum(x => x.Key.Amount);
var abc2 = from dlist in db.DebtorTransactions.ToList()
join cjt in db.CarJackaTrackas on dlist.ProductID equals cjt.pkfCjtID
join ag in db.Agents on cjt.AgentID equals ag.pkfAgentID
join sr in db.SalesReps on cjt.SalesRepId equals sr.pkfSrID
where dlist.TransTypeID == 0
select new
{
dlist.Amount,
dlist.TransTypeID,
name = ag.Name,
ag.pkfAgentID,
sr.pkfSrID,
enter code here` salesnam = sr.Name
} into objabc
group objabc by new
{
objabc.TransTypeID,
objabc.name,
objabc.salesnam,
objabc.Amount
};
var amt2 = abc1.Sum(x => x.Key.Amount);
//var result1=
return View();
i am new to linq, this query is working but i need to get the sum of Amount where dlist.TransTypeID == 0 and where dlist.TransTypeID == 1 by just single query. may anybody help me? thanks in advance
Here's a trimmed down example of how you can do it. You can add the joins if they are necessary, but I'm not clear on why you need some of the extra join values.
var transTypeAmountSums = (from dlist in db.DebtorTransactions
group dlist by dlist.TransTypeId into g
where g.Key == 0 || g.Key == 1
select new
{
TransTypeId = g.Key,
AmountSum = g.Sum(d => d.Amount)
}).ToDictionary(k => k.TransTypeId, v => v.AmountSum);
int transTypeZeroSum = transTypeAmountSums[0];
int transTypeOneSum = transTypeAmountSums[1];
A couple of things to note:
I removed ToList(). Unless you want to bring ALL DebtorTransactions into memory then run a Linq operation on those results, you'll want to leave that out and let SQL take care of the aggregation (it's much better at it than C#).
I grouped by dlist.TransTypeId only. You can still group by more fields if you need that, but it was unclear in the example why they were needed so I just made a simplified example.

how to combine two linq to entity queries in just one query?

var CJTDebTransaction = from d in db.DebtorTransactions
join c in db.CarJackaTrackas on d.ProductID equals c.pkfCjtID
join a in db.Agents on c.AgentID equals a.pkfAgentID
join s in db.SalesReps on c.SalesRepId equals s.pkfSrID
where d.TransTypeID==1 && d.Product==1
select new { d.Amount, d.TransTypeID, Name=a.Name.Trim(), a.pkfAgentID,s.pkfSrID,salesrepName=s.Name} into debtRec
group debtRec by new { debtRec.TransTypeID, debtRec.Name, debtRec.pkfAgentID,debtRec.salesrepName,debtRec.pkfSrID} into debtRecGroup
orderby debtRecGroup.Key.Name
select new
{
Sum= debtRecGroup.Sum(model=>model.Amount),
TransTypeId=debtRecGroup.Key.TransTypeID ,
AgentId=debtRecGroup.Key.pkfAgentID,
AgentName=debtRecGroup.Key.Name,
SalesrepId=debtRecGroup.Key.pkfSrID,
SalesRepName=debtRecGroup.Key.salesrepName
};
var WntyDebTransaction = from d in db.DebtorTransactions
join w in db.Warranties on d.ProductID equals w.Id
join a in db.Agents on w.fldAgentID equals a.pkfAgentID
join s in db.SalesReps on w.fldSrId equals s.pkfSrID
where d.TransTypeID == 1 && d.Product == 0
select new { d.Amount, d.TransTypeID, Name=a.Name.Trim(), a.pkfAgentID, s.pkfSrID, salesrepName = s.Name } into debtRec
group debtRec by new { debtRec.TransTypeID, debtRec.Name, debtRec.pkfAgentID, debtRec.salesrepName, debtRec.pkfSrID } into debtRecGroup
orderby debtRecGroup.Key.Name
select new
{
Sum = debtRecGroup.Sum(model => model.Amount),
TransTypeId = debtRecGroup.Key.TransTypeID,
AgentId = debtRecGroup.Key.pkfAgentID,
AgentName = debtRecGroup.Key.Name.Trim(),
SalesrepId = debtRecGroup.Key.pkfSrID,
SalesRepName = debtRecGroup.Key.salesrepName
}
I need to get the output in just one query, i new to linq to entity. i need the result like:- AgentName SalesRepName Debit Total(the total of amount where Product == 0) Credit Total(total of amount where Product==1) Outstanding Total(the difference between Debit Total and Credit Total). any suggestion will be appreciable. thanks in advance :)

In join want to get not matched records

Work on DF 4 vs 2010.Face problem on join on SalSalesOrderDetail with SalSalesOrderFinancial table.
In SalSalesOrderFinancial one record have SalesOrderDetailID=null. Want to get those records whose SalesOrderDetailID is not present in SalSalesOrderFinancial.
To get desired out put write bellow linq syntax,it’s working .Looking for better join syntax .Is there any way to get desired in one join.
var tempBDwithSODetail = (from p in this.Context.SalSalesOrderFinancials
where p.SalesOrderDetailID != null
select p.SalesOrderDetailID).AsEnumerable();
var tempBDwithOutSODetail = (from p in this.Context.SalSalesOrderFinancials where p.SalesOrderDetailID == null select p).AsEnumerable();
var querySOD = (this.Context.SalSalesOrderDetails.Where(item => !tempBDwithSODetail.Contains(item.SalesOrderDetailID))).AsEnumerable();
var tempBDetail = (from p in querySOD
join q in tempBDwithOutSODetail on p.SalesOrderID equals q.SalesOrderID
where q.SalesOrderDetailID == null
select new
{
q.SalesOrderID,
p.SalesOrderDetailID,
q.CurrencyID,
q.BillingPolicyID,
q.BillTypeID,
q.BillingTypeID
}).AsEnumerable();
If have any query please ask.Thanks in advanced.
if i got you, you just need to simple left join between SalSalesOrderDetail and SalSalesOrderFinancial...
var query = (from u in this.Context.SalSalesOrderDetail
join t in this.Context.SalSalesOrderFinancials
on u.SalesOrderDetailID equals t.SalesOrderDetailID into JoinedList
from t in JoinedList.DefaultIfEmpty()
select new
{
SalSalesOrderDetail = t,
SalSalesOrderFinancials = u
})
.Where(u => u.SalSalesOrderFinancials == null)
.ToList();

LINQ 2 lefts joins with Sum

I am trying to do a relatively straight forward SQL query with linq:
SELECT ir.resource_id, r.first_name, r.surname, rt.job_title, SUM(plan_ts_hours), SUM(ts_hours) FROM tbl_initiative_resource ir
INNER JOIN tbl_resource r ON ir.resource_id = r.resource_id
INNER JOIN tbl_resource_type rt ON rt.resource_type_id = r.resource_type_id
LEFT JOIN tbl_plan_timesheet pts on pts.resource_id = ir.resource_id AND pts.initiative_id = ir.initiative_id
LEFT JOIN tbl_timesheet ts on ts.resource_id = ir.resource_id AND ts.initiative_id = ir.initiative_id
WHERE ir.initiative_id = 111
GROUP BY ir.resource_id, r.first_name, r.surname, rt.job_title
After reading this blog: http://smehrozalam.wordpress.com/2010/04/06/linq-how-to-build-complex-queries-utilizing-deferred-execution-and-anonymous-types/
I came up with the following linq:
var query = (from initRes in Context.tbl_initiative_resource
join res in Context.tbl_resource on initRes.resource_id equals res.resource_id
join resType in Context.tbl_resource_type on res.resource_type_id equals resType.resource_type_id
from tsheet in Context.tbl_timesheet.Where(x => x.resource_id == initRes.resource_id).Where(x => x.initiative_id == initRes.initiative_id).DefaultIfEmpty()
from plannedtsheet in Context.tbl_plan_timesheet.Where(x => x.resource_id == initRes.resource_id).Where(x => x.initiative_id == initRes.initiative_id).DefaultIfEmpty()
where initRes.initiative_id == initiativeID
group new { ID = res.resource_id, ResourceType = resType.job_title, Times = tsheet, P = plannedtsheet } by initRes.resource_id into g
select new
{
ResourceID = g.Key,
Hours = g.Sum(x => (decimal?)x.Times.ts_hours),
PlannedHours = g.Sum(x => (decimal?)x.P.plan_ts_hours)
}).ToList();
Any ideas on how I can access the ResourceType when selecting the new anonymous type?
ResourceType is part of the the grouping key, so g.Key.ResourceType should do it.
(Check out the type of ResouceID in the results, as you've assigned it g.Key it will be an instance of the (anonymous) type created in the group clause.

Resources