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();
Related
var Getdetails = (from p in XYZDb.tblPulls
join
ro in XYZDb.tblRentalOrders
on p.AffCode equals ro.AffCode.Value
join
tpsb in XYZDb.tblPullSheetBatchProcessings
on p.PullNo.ToString() equals tpsb.PullSheet
select new
{
PullNos = p.PullNo,
AffCode = p.AffCode,
TotalItems = p.TotalItems,
p.PostedOn,
p.UpdatedOn,
p.IsPrinted,
BatchName = tpsb.BatchName
})
.Where(i => i.PostedOn >= from_date && i.PostedOn <= to && i.IsPrinted != null).Distinct();
In the above code only the pullno having BatchName are coming, i want to retrieve all the pullno within that timezone, and if it is batched, then the BatchName will also appear. I am stuck on that. Any kind of help will be appreciated. Feel free to ask any question.
Use left outer join,
var Getdetails = (from p in XYZDb.tblPulls
join
ro in XYZDb.tblRentalOrders
on p.AffCode equals ro.AffCode.Value
join
tpsb in XYZDb.tblPullSheetBatchProcessings
on p.PullNo.ToString() equals tpsb.PullSheet into pt
from batch in pt.DefaultIfEmpty()
select new
{
PullNos = p.PullNo,
AffCode = p.AffCode,
TotalItems = p.TotalItems,
p.PostedOn,
p.UpdatedOn,
p.IsPrinted,
BatchName = (batch == null ? String.Empty : batch.BatchName )
})
.Where(i => i.PostedOn >= from_date && i.PostedOn <= to && i.IsPrinted != null).Distinct();
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();
Im using ASP MVC, I have this LINQ to get employees DTR:
IEnumerable<DatatablesViewModel> viewmodel =
(from a in db.tHREmployees
join b in db.tTADTRs on a.EmpID equals b.EmpID
join c in db.tHRJobGrades on a.JobGrdID equals c.JobGrdID
join d in db.tTAShifts on b.ShftID equals d.ShftID
join e in db.tTADays on b.DayID equals e.DayID
where (b.LogDt >= PeriodDates.FromDt && b.LogDt <= PeriodDates.ToDt)
select new DatatablesViewModel
{
EmpID = a.EmpID,
Name = a.LastNm + ", " + a.FirstNm + ", " + a.MiddleNm,
JobGradeDesc = c.JobGrdDesc,
ShftNm = d.ShftNm,
DayType = e.DayNm,
LogDT = b.LogDt,
LogIn = b.LogIn,
LogOut = b.LogOut,
Absent = b.AbsDay,
Work = b.WorkHr,
Late = b.LateHr,
Overtime = b.OTHr,
Undertime = b.OTHr,
Nightdiff = b.NDHr,
NightPrem = b.NPHr,
ApprovedOT = b.AppOT,
ApprovedOB = b.AppOB,
ApprovedCoa = b.AppCOA,
ApprovedCs = b.AppCS,
Exception = b.ExcptStatus
}).OrderBy(x => x.EmpID);
In my view i have dropdown menu that has employee names with 'ALL' option.
I want to add a condition inside 'where' in above code somthing like:
if(parameter.selectedEmp != "ALL"){
Where(x => x.EmpID == param.CustomParam_EmpID) <-- add this filter
}
I want to select only what is needed in my query to avoid delay.
You don't need to add it in the Where clause directly. The IEnumerable and your LINQ query are only evaluated once you start to iterate through the collection. You could simply do something like this:
var relevantVMObjects =
(from a in db.tHREmployees
join b in db.tTADTRs on a.EmpID equals b.EmpID
join c in db.tHRJobGrades on a.JobGrdID equals c.JobGrdID
join d in db.tTAShifts on b.ShftID equals d.ShftID
join e in db.tTADays on b.DayID equals e.DayID
where (b.LogDt >= PeriodDates.FromDt && b.LogDt <= PeriodDates.ToDt)
select new DatatablesViewModel
{
EmpID = a.EmpID,
Name = a.LastNm + ", " + a.FirstNm + ", " + a.MiddleNm,
JobGradeDesc = c.JobGrdDesc,
ShftNm = d.ShftNm,
DayType = e.DayNm,
LogDT = b.LogDt,
LogIn = b.LogIn,
LogOut = b.LogOut,
Absent = b.AbsDay,
Work = b.WorkHr,
Late = b.LateHr,
Overtime = b.OTHr,
Undertime = b.OTHr,
Nightdiff = b.NDHr,
NightPrem = b.NPHr,
ApprovedOT = b.AppOT,
ApprovedOB = b.AppOB,
ApprovedCoa = b.AppCOA,
ApprovedCs = b.AppCS,
Exception = b.ExcptStatus
}).OrderBy(x => x.EmpID);
if(parameter.selectedEmp != "ALL")
relevantVMObjects = relevantVMObjects.Where(x => x.EmpID == param.CustomParam_EmpID);
IEnumerable<DatatablesViewModel> viewmodel = relevantVMObjects;
You can do this by OR condition
string selectedEmp=parameter.selectedEmp;
IEnumerable<DatatablesViewModel> viewmodel =
(from a in db.tHREmployees
join b in db.tTADTRs on a.EmpID equals b.EmpID
join c in db.tHRJobGrades on a.JobGrdID equals c.JobGrdID
join d in db.tTAShifts on b.ShftID equals d.ShftID
join e in db.tTADays on b.DayID equals e.DayID
where (b.LogDt >= PeriodDates.FromDt && b.LogDt <= PeriodDates.ToDt) &&
(selectedEmp != "ALL" || a.EmpID == param.CustomParam_EmpID)
select new DatatablesViewModel
{
...
}
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();
How do I write a sub-select in LINQ.
If I have a list of customers and a list of orders I want all the customers that have no orders.
This is my pseudo code attempt:
var res = from c in customers
where c.CustomerID ! in (from o in orders select o.CustomerID)
select c
How about:
var res = from c in customers
where !orders.Select(o => o.CustomerID).Contains(c.CustomerID)
select c;
Another option is to use:
var res = from c in customers
join o in orders
on c.CustomerID equals o.customerID
into customerOrders
where customerOrders.Count() == 0
select c;
Are you using LINQ to SQL or something else, btw? Different flavours may have different "best" ways of doing it
If this is database-backed, try using navigation properties (if you have them defined):
var res = from c in customers
where !c.Orders.Any()
select c;
On Northwind, this generates the TSQL:
SELECT /* columns snipped */
FROM [dbo].[Customers] AS [t0]
WHERE NOT (EXISTS(
SELECT NULL AS [EMPTY]
FROM [dbo].[Orders] AS [t1]
WHERE [t1].[CustomerID] = [t0].[CustomerID]
))
Which does the job quite well.
var result = (from planinfo in db.mst_pointplan_info
join entityType in db.mst_entity_type
on planinfo.entityId equals entityType.id
where planinfo.entityId == entityId
&& planinfo.is_deleted != true
&& planinfo.system_id == systemId
&& entityType.enity_enum_id == entityId
group planinfo by planinfo.package_id into gplan
select new PackagePointRangeConfigurationResult
{
Result = (from planinfo in gplan
select new PackagePointRangeResult
{
PackageId = planinfo.package_id,
PointPlanInfo = (from pointPlanInfo in gplan
select new PointPlanInfo
{
StartRange = planinfo.start_range,
EndRange = planinfo.end_range,
IsDiscountAndChargeInPer = planinfo.is_discount_and_charge_in_per,
Discount = planinfo.discount,
ServiceCharge = planinfo.servicecharge,
AtonMerchantShare = planinfo.aton_merchant_share,
CommunityShare = planinfo.community_share
}).ToList()
}).ToList()
}).FirstOrDefault();
var res = (from c in orders where c.CustomerID == null
select c.Customers).ToList();
or Make Except()