Getting Total Record by Group by in Linq - c#

I have one query in SQL, want to convert it to Linq. My Query is :
select count(tbs.tbsid) as CNTSeats,tbm.BusNo
from tdp_tourpackageschedule tps
join tdp_tourpackage tp on tp.TourID = tps.FK_TourID
join tdp_tourbusseats tbs on tbs.tbsid = tps.fk_tbsid
join tdp_tourbusmaster tbm on tbm.tbid = tbs.fk_tbid
where fk_tdid = #FKTDID and fk_TourID = #FKTourID and IsOpen = 1
group by tbm.BusNo
I tried this Code:
var tourAvail = (from ts in entities.tdp_TourPackageSchedule
join tp in entities.tdp_TourPackage on ts.FK_TourID equals tp.TourID
join tbs in entities.tdp_TourBusSeats on ts.FK_TBSID equals tbs.TBSID
join tb in entities.tdp_TourBusMaster on tbs.FK_TBID equals tb.TBID
where ts.FK_TDID == TDID && ts.FK_TourID == TourID && ts.IsOpen == 1
group tb by tb.BusNo into cnt
select new
{
//BusNo = cnt.bu
//Count = cnt.Select(x => x.tdp_TourBusSeats).Distinct().Count()
});
I don't know how to get count of records, anyone can help ?

Do :
var tourAvail = (from ts in entities.tdp_TourPackageSchedule
join tp in entities.tdp_TourPackage on ts.FK_TourID equals tp.TourID
join tbs in entities.tdp_TourBusSeats on ts.FK_TBSID equals tbs.TBSID
join tb in entities.tdp_TourBusMaster on tbs.FK_TBID equals tb.TBID
where ts.FK_TDID == TDID && ts.FK_TourID == TourID && ts.IsOpen == 1
group tb by tb.BusNo into cnt
select new
{
BusNo = cnt.Key,
Count = cnt.Count()
}).ToList();

Related

What's wrong with this LINQ?

I am using LINQ TO Entities & need to use Union operator.
This is my raw sql query.
(select DISTINCT c.DocumentId from [sDocument].[tDocumentStatus] c
inner join [sDocument].[tTOCStructure] d on c.DocumentId = d.FolderID
inner join [sDocument].[tAudit] e on c.DocumentId = e.FolderID
where d.FolderType = 2 and d.isDeleted = 0 and d.ClientID = 9 and e.AuditDescriptionID != 10)
Union
(select DISTINCT c.FolderID from [sDocument].[tTOCStructure] c
inner join [sDocument].[tAudit] e on c.DocumentId = e.FolderID
where c.FolderType = 2 and c.isDeleted = 0 and c.ClientID = 9 )
When I run the above sql, I get around 45 records. That's right as well
Below is LINQ for the same requirement.
IQueryable<DocumentListMapper> query = (
from c in entities.tDocumentStatus
join d in entities.tTOCStructures on c.DocumentId equals d.FolderID
join e in entities.tAudits on c.DocumentId equals e.FolderID
where d.FolderType == 2 && d.isDeleted == false && d.ClientID == clientId && e.AuditDescriptionID != 10
select new DocumentListMapper()
{
DocumentId = c.DocumentId,
DocumentName = d.CheckoutFolderName,
PublishDate = c.AssignedDate
}).Distinct().Union(
from c in entities.tTOCStructures
join e in entities.tAudits on c.FolderID equals e.FolderID
where c.FolderType == 2 && c.isDeleted == false && c.ClientID == clientId
select new DocumentListMapper()
{
DocumentId = c.FolderID,
DocumentName = c.CheckoutFolderName,
PublishDate = e.TaskDateTime
}).Distinct().OrderBy(x => x.PublishDate).Skip(pager * 50).Take(50);
But this LINQ returns more than 2500 records. This is not the desired records.
What's wrong in my LINQ??

Converting an SQL Containing inner and Outer Joins into Linq

I need to convert an SQL query to Linq/Lambda expression, I am trying doing the same but not getting the desired results.
SQL:
SELECT b.*, n.notes
FROM Goal_Allocation_Branch as b
INNER JOIN Goal_Allocation_Product as g
on b.Product = g.ProductID
and b.Year = g.Year
left join Goal_Allocation_Branch_Notes as n
on b.branchnumber = n.branch
and n.year = ddlYear
WHERE b.Year = ddlYear
and g.Show = 1
and branchnumber = ddlBranch
I am new to Linq , I am getting error on Join Clause , and X is not containing any data from first Join
var result = (from br in _DB_Branches.Goal_Allocation_Branches
join pr in _DB_Product.Goal_Allocation_Products on new { br.Product, br.Year } equals new {Product= pr.ProductID, Year= pr.Year }
join n in _DB_Notes.Goal_Allocation_Branch_Notes.Where(n => n.Year == ddlYear) on br.BranchNumber equals n.Branch into Notes
from x in Notes.DefaultIfEmpty()
select new BranchNotesViewModel
{
Year = x.Year,
BranchNumber = x.Branch,
ProductID = x.ProdID
}
).ToList();
Update: My First Join clause initially giving error "The type of one of the expression in Join Clause is incorrect " is resolved, when I Changed On Clause
from
"on new { br.Product, br.Year } equals new {pr.ProductID, pr.Year}"
"on new { br.Product, br.Year } equals new {Product=pr.ProductID,Year= pr.Year}"
still not getting desired results as expected from above SQL query. Please advise..
It should be something like this (see note):
var result =
(from br in _DB_Branches.Goal_Allocation_Branches
join pr in _DB_Product.Goal_Allocation_Products
on br.Product equals pr.ProductID
from n in _DB_Notes.Goal_Allocation_Branch_Notes.Where(x=>
x.branch == br.branchnumber
&& x.year == ddlYear
).DefaultIfEmpty()
where
br.Year == ddlYear
&& and br.Year == pr.Year
&& pr.Show == 1
&& br.branchnumber == ddlBranch
select new BranchNotesViewModel
{
Year = ...,
BranchNumber = ...,
ProductID = ...
}
).ToList();
Note: Change the select, to the properties you want.
Edit: fixed some syntax errors.
I finally figured out the correct answer. Working absolutely fine
var result = (from br in _DB_Branches.Goal_Allocation_Branches
join pr in _DB_Product.Goal_Allocation_Products on new { br.Product, br.Year } equals new { Product = pr.ProductID, Year = pr.Year }
join n in _DB_Notes.Goal_Allocation_Branch_Notes.Where(n=>n.Year==ddlYear) on br.BranchNumber equals n.Branch into Notes
where br.Year==ddlYear
&& pr.Show== true
&& br.BranchNumber==ddlBranch
from x in Notes.DefaultIfEmpty()
select new BranchNotesViewModel
{
Year=x.Year,
BranchNumber=x.Branch,
ProductID=br.Product,
Notes = x.Notes,
//All other fields needed
}
).ToList();

How to optimize linq query?

I have difficulty in getting an average score of students in each department.
while every department there are many faculties, each faculty there are many courses, each course there are many students, and every student has a lot of value.
the query that I have made, I get quite a lot of the time constraints that are required to display the same data capture.
please help to optimize the query that I made this.
double TotalNilaiMutu = 0;
double JumSKS = 0;
double ipkMhs = 0;
double totalIPK = 0;
var queryDepartemen = (from so in StrukturOrganisasis
join dp in Departemens on so.ID equals dp.ID
orderby dp.ID
select new{dp.ID, so.Inisial, so.Nama}).ToList();
foreach(var departemen in queryDepartemen){
var queryMayor = (from my in Mayors
where my.DepartemenID == departemen.ID && my.StrataID == 2
select my.ID).ToList();
var queryMhs = (from ms in MahasiswaSarjanas
where queryMayor.Contains(ms.MayorID) &&
(
from sm in StatusMahasiswas
where
(
from ts in TahunSemesters
where ts.TahunAwal == 2013
select ts.ID
)
.Contains(sm.TahunSemesterID)
select sm.NIM
)
.Contains(ms.NIM)
select ms.NIM).ToList();
ipkMhs = 0;
foreach(var nim in queryMhs){
var queryNilai = (from kr in KRS
join hm in HurufMutus on kr.HurufMutuID equals hm.ID
join kur in
(
from ku in Kurikulums
join mk in MataKuliahs on ku.MataKuliahID equals mk.ID
select new {ku.ID, mk.Nama, mk.SKS}
)
on kr.KurikulumID equals kur.ID
where kr.NIM==nim
select new {
nilai = hm.NilaiMutu * kur.SKS,
sks = kur.SKS
});
TotalNilaiMutu = 0;
JumSKS = 0;
foreach(var ipk in queryNilai){
TotalNilaiMutu += ipk.nilai;
JumSKS += ipk.sks;
}
if(double.IsNaN(TotalNilaiMutu/JumSKS)) ipkMhs+=0;
else ipkMhs += TotalNilaiMutu/JumSKS;
}
if(double.IsNaN(ipkMhs/queryMhs.Count())) totalIPK=0;
else totalIPK=ipkMhs/queryMhs.Count();
Console.WriteLine(departemen.Nama +" -> "+ totalIPK +" : "+ ipkMhs +" / "+queryMhs.Count());
}
Have you tried adding AsParallel()?
var queryDepartemen = (from so in StrukturOrganisasis.AsParallel()
join dp in Departemens on so.ID equals dp.ID
orderby dp.ID
select new{dp.ID, so.Inisial, so.Nama}).ToList();
foreach(var departemen in queryDepartemen.AsParallel()){
var queryMayor = (from my in Mayors
where my.DepartemenID == departemen.ID && my.StrataID == 2
select my.ID).ToList();
var queryMhs = (from ms in MahasiswaSarjanas.AsParallel()
where queryMayor.Contains(ms.MayorID) &&
(
from sm in StatusMahasiswas
where
(
from ts in TahunSemesters
where ts.TahunAwal == 2013
select ts.ID
)
.Contains(sm.TahunSemesterID)
select sm.NIM
)
.Contains(ms.NIM)
select ms.NIM).ToList();

How to Use Data Inside Var in Linq?

I want to sum records using Group by from the all data inside "result view".
can anyone guide me for this.!
Here is My Code
var tData1 = (from i in _data.Transactions
join y in _data.DeviceInformations on i.DeviceInfoId equals y.DeviceInfoId
join u in _data.AccountDevices on y.DeviceInfoId equals u.DeviceInfoId
where y.Active == true && u.AccountId == 1000001 && u.Active == true
group i by i.DeviceInfoId into g
select g.OrderByDescending(t => t.DateCreated)).ToList();
foreach (var xCo in tData1)
{
//I am getting Data in xCo
}
Based on #Nayeem Mansoori solution you can try this.
var tData1 = (from i in _data.Transactions
join y in _data.DeviceInformations on i.DeviceInfoId equals y.DeviceInfoId
join u in _data.AccountDevices on y.DeviceInfoId equals u.DeviceInfoId
where y.Active == true && u.AccountId == 1000001 && u.Active == true
group i by i.DeviceInfoId into g
select new {Id = DeviceInfoId, sum = g.Sum(x=>x.DeviceInfoId)};

why does LINQ To SQL result in SQL like this?

When LINQ translates the below syntax to SQL, the (inner) where clause gets moved to the outer-most query. That's super-unfriendly to the database. I wrote this like Hibernate's HQL (is this appropriate?), and I've written SQL for many moons.
Can anyone help explain what gives, or point me in the way of a resolution?
var rc = (
from dv in (
from dv_j in (
from x in adc.JobManagement
join j in adc.Job on x.JobId equals j.JobId
join js in adc.JobStatus on j.StatusId equals js.JobStatusId
join cm in adc.ClientManagement on j.ClientId equals cm.ClientId
join o in adc.User on cm.UserId equals o.UserId
join jm in adc.JobManagement on j.JobId equals jm.JobId
where
(x.UserId == aid || cm.UserId == aid)
&& (j.StatusDate == null || j.StatusDate >= getFromDate())
&& (jm.ManagementRoleCode == MR_MANAGER)
select new
{
j.JobId,
Job = j.InternalName == null ? j.ExternalName : j.InternalName,
JobStatusDate = j.StatusDate,
JobStatus = js.Code,
Owner = o.Username,
Role = jm.ManagementRoleCode
})
join s in adc.Submission on dv_j.JobId equals s.JobId into dv_s
from s in dv_s.DefaultIfEmpty()
select new
{
dv_j.JobId,
dv_j.Job,
dv_j.JobStatusDate,
dv_j.JobStatus,
dv_j.Owner,
dv_j.Role,
s.SubmissionId,
s.CandidateId,
s.SubmissionDate,
StatusDate = s.StatusDate,
StatusId = s.StatusId
})
join c in adc.Candidate on dv.CandidateId equals c.CandidateId into dv_c
join ss in adc.SubmissionStatus on dv.StatusId equals ss.SubmissionStatusId into dv_ss
from c in dv_c.DefaultIfEmpty()
from ss in dv_ss.DefaultIfEmpty()
orderby
dv.StatusId == null ? dv.StatusDate : dv.JobStatusDate descending,
dv.Job,
c.LastName,
c.NickName,
c.FirstName
select new Projects
{
Id = dv.JobId,
Project = dv.Job,
Submitted = dv.SubmissionDate,
Candidate = FormatIndividual(c.LastName, c.FirstName, c.NickName),
Status = dv.StatusId == null ? ss.Code : dv.JobStatus,
StatusDate = dv.StatusId == null ? dv.StatusDate : dv.JobStatusDate,
Role = dv.Role,
Owner = dv.Owner
});
Try breaking down the one statement into two. This would work as it cannot move the where to a place that doesn't exist yet. This does make multiple round trips to the database, but it is better than having most of several large tables being joined then culled. I would try this:
var inMemoryTable = (
from x in adc.JobManagement
join j in adc.Job on x.JobId equals j.JobId
join js in adc.JobStatus on j.StatusId equals js.JobStatusId
join cm in adc.ClientManagement on j.ClientId equals cm.ClientId
join o in adc.User on cm.UserId equals o.UserId
join jm in adc.JobManagement on j.JobId equals jm.JobId
where
(x.UserId == aid || cm.UserId == aid)
&& (j.StatusDate == null || j.StatusDate >= getFromDate())
&& (jm.ManagementRoleCode == MR_MANAGER)
select new
{
j.JobId,
Job = j.InternalName == null ? j.ExternalName : j.InternalName,
JobStatusDate = j.StatusDate,
JobStatus = js.Code,
Owner = o.Username,
Role = jm.ManagementRoleCode
});
var rc = (
from dv in (
from dv_j in inMemoryTable
join s in adc.Submission on dv_j.JobId equals s.JobId into dv_s
from s in dv_s.DefaultIfEmpty()
select new
{
dv_j.JobId,
dv_j.Job,
dv_j.JobStatusDate,
dv_j.JobStatus,
dv_j.Owner,
dv_j.Role,
s.SubmissionId,
s.CandidateId,
s.SubmissionDate,
StatusDate = s.StatusDate,
StatusId = s.StatusId
})
join c in adc.Candidate on dv.CandidateId equals c.CandidateId into dv_c
join ss in adc.SubmissionStatus on dv.StatusId equals ss.SubmissionStatusId into dv_ss
from c in dv_c.DefaultIfEmpty()
from ss in dv_ss.DefaultIfEmpty()
orderby
dv.StatusId == null ? dv.StatusDate : dv.JobStatusDate descending,
dv.Job,
c.LastName,
c.NickName,
c.FirstName
select new Projects
{
Id = dv.JobId,
Project = dv.Job,
Submitted = dv.SubmissionDate,
Candidate = FormatIndividual(c.LastName, c.FirstName, c.NickName),
Status = dv.StatusId == null ? ss.Code : dv.JobStatus,
StatusDate = dv.StatusId == null ? dv.StatusDate : dv.JobStatusDate,
Role = dv.Role,
Owner = dv.Owner
});

Categories

Resources