LINQ Left Join with wrong response - c#

I need to do a left join using LINQ.
I'm using this code:
var query = (from Geral in listEstadosGeral
join Coberto in listEstadoCoberto
on Geral.Id equals Coberto.Id
into temp
from j in temp.DefaultIfEmpty()
select new Estado()
{
Sigla = Geral.Sigla,
Nome = Geral.Nome
}).ToList();
In listEstadoGeral I have 27 records and in listEstadoCoberto I have 5 records.
The query has 27 records.
What is wrong with this code?

If you want to get the records that are present in listEstadosGeral that are not in listEstadoCoberto :
var result = listEstadosGeral.Where(p => !listEstadoCoberto.Any(p2 => p2.ID == p.ID)).ToList();

var query = (from Geral in listEstadosGeral
join Coberto in listEstadoCoberto
on Geral.Id equals Coberto.Id
select new Estado()
{
Sigla = Geral.Sigla,
Nome = Geral.Nome
}).ToList();

Related

How to rewrite sql query to linq

I'm trying to rewrite sql query to linq but can't do it myself.
The most problem for me is to get I,II and III aggregated values.
Sql query:
select o.Name,t.TypeID, SUM(e.I),SUM(e.II),SUM(e.III) from Expenditure e
join Finance f on f.FinanceId = e.FinanceId
join FinanceYear fy on fy.FinanceYearId = f.FinanceYearId and fy.StatusId = 1
join Project p on p.ProjectId = fy.ProjectId
join Organization o on o.OrganizationId = p.OrganizationId
join Type t on t.TypeID = p.TypeID
where fy.Year = 2018
group by o.Name,s.TypeID
and what I have done so far is:
var x = (from e in _db.Expenditures
join f in _db.Finances on e.FinanceId equals f.FinanceId
join fy in _db.FinanceYears on f.FinanceYearId equals fy.FinanceYearId and fy.StatusId = 1 // this does not work, cant join on multiple conditions?
join p in _db.Projects on fy.ProjectId equals p.ProjectId
join o in _db.Organizations on p.OrganizationId equals o.OrganizationId
join s in _db.Types on p.TypeId equals s.TypeId
group new { o, s } by new { o.OrganizationId, s.TypeId }
into grp
select new AggModel
{
OrganizationId = grp.Key.OrganizationId,
TypeId = grp.Key.TypeId,
I = ?,
II = ?,
III = ?,
}
);
Try something like this:
group new { e, o, s } by new { o.OrganizationId, s.TypeId }
into grp
select new AggModel
{
OrganizationId = grp.Key.OrganizationId,
TypeId = grp.Key.TypeId,
I = grp.Sum(a => a.e.I),
II = grp.Sum(a => a.e.II),
III = grp.Sum(a => a.e.III),
}
You'll need to adjust the right side of the lambda to navigate to the correct property.
You Need to use the Group by for aggregation methods.
Check the below link for more Knowledge.
How to use aggregate functions in linq with joins?

How to do concat or group by in linq? I am getting multiples values want to concat the data by ','

my Query:
var s = entities.Doctors.SingleOrDefault(x => x.AreaId == id);
var z = (from x in entities.Doctors
join y in entities.Areas on x.AreaId equals y.AreaId
join s1 in entities.Availabilties on s.D_Id equals s1.DoctorId
join s2 in entities.Eductions on s.D_Id equals s2.DoctorId
join s3 in entities.DoctorSpecialities on s.D_Id equals s3.DoctorId
join s4 in entities.Specialities on s3.SpecialityId equals s4.SpecialityId
join s5 in entities.DaysDetails on s1.DaysId equals s5.DaysId
join s6 in entities.Degrees on s2.DegreeId equals s6.DegreeId
where x.AreaId.Equals(id)
select new DoctorDisplay
{
D_name = x.D_Name,
D_address = x.D_Address,
D_Area = y.AreaName,
D_Contact1 = x.D_Contactone,
D_Contact2 = x.D_Contacttwo,
D_fax = x.D_Faxno,
D_SpecialityName = s4.SpecialityName,
D_Availstarttime = s1.StartTime,
D_Availlasttime = s1.LastTime,
D_Availday= s5.DaysName,
D_DegreeName = s6.DegreeName,
D_Awards = x.D_Address,
D_Status = x.D_Status
}).ToList();
****Getting Output****
[{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Dietician","D_Availstarttime":"9PM","D_Availlasttime":"11PM","D_Availday":"Sunday","D_DegreeName":"MBBS","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Dietician","D_Availstarttime":"9PM","D_Availlasttime":"11PM","D_Availday":"Sunday","D_DegreeName":"Dentistdegree","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Ayurveda","D_Availstarttime":"9PM","D_Availlasttime":"11PM","D_Availday":"Sunday","D_DegreeName":"MBBS","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Ayurveda","D_Availstarttime":"9PM","D_Availlasttime":"11PM","D_Availday":"Sunday","D_DegreeName":"Dentistdegree","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Dietician","D_Availstarttime":"4AM","D_Availlasttime":"11AM","D_Availday":"Monday","D_DegreeName":"MBBS","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Dietician","D_Availstarttime":"4AM","D_Availlasttime":"11AM","D_Availday":"Monday","D_DegreeName":"Dentistdegree","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Ayurveda","D_Availstarttime":"4AM","D_Availlasttime":"11AM","D_Availday":"Monday","D_DegreeName":"MBBS","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Ayurveda","D_Availstarttime":"4AM","D_Availlasttime":"11AM","D_Availday":"Monday","D_DegreeName":"Dentistdegree","D_Awards":"block123","D_Status":"Available"}]
Group_concat on the basis of Education Id, DoctorspecialitiesID, Avaibilities Id,
Image of Input and desire Output
Looking at you example output, it looks less like you want to "concat the data by ','" as much as you want to convert it to JSON.
Inwhichcase, you'd probably be better off using a tool like Newtonsoft's JSON.NET
UPDATE (based on comments):
Assume doctors is the result of the query given in question.
var output =
from d in doctors
group d by new { d.D_NAME, d.D_Area } into dg
select new DoctorDisplay
{
D_NAME = dg.Key.D_NAME,
D_Area = dg.Key.D_Area,
D_SpecialityName = String.Join(",", dg.Select(d => d.D_SpecialityName).Distinct()),
D_DegreeName = String.Join(",", dg.Select(d => d.D_DegreeName).Distinct())
};

linq left join with filtering in joined

I am getting duplication meals here
IEnumerable<DTOHotMealsPrice> lst = (from m in this.dbEntity.HOT_MEALS
join ml in this.dbEntity.HOT_MEALS_PRICE on m.MEALSID equals ml.MEALSID into mls
from mls1 in mls.DefaultIfEmpty()
where mls1.HOTID==hotelId
select new DTOHotMealsPrice
{
MEALSID = m.MEALSID,
MEALSNAME = m.MEALSNAME,
CHPRICE = mls1.CHPRICE,
PRICE = mls1.PRICE,
HOTID = mls1.HOTID
}).Distinct().ToList();
I want to list all HOT_MEALS and also join with
HOT_MEALS_PRICE when a mealsid reference on it
When mls1.HOTID==hotelId, this will getting innerjoin results
How could it will a proper result
Two Way solve Solution
Remove Where Case
Add where Case In Join table
Show for Where Case Blow Linq Query
first Query
IEnumerable<DTOHotMealsPrice> lst = (from m in this.dbEntity.HOT_MEALS
join ml in this.dbEntity.HOT_MEALS_PRICE.where(c=>c.HOTID==hotelId) on m.MEALSID equals ml.MEALSID into mls
from mls1 in mls.DefaultIfEmpty()
select new DTOHotMealsPrice
{
MEALSID = m.MEALSID,
MEALSNAME = m.MEALSNAME,
CHPRICE = mls1.CHPRICE,
PRICE = mls1.PRICE,
HOTID = mls1.HOTID
}).Distinct().ToList();
Second is:
IEnumerable<DTOHotMealsPrice> lst = (from m in this.dbEntity.HOT_MEALS
join ml in this.dbEntity.HOT_MEALS_PRICE on m.MEALSID equals ml.MEALSID into mls
from mls1 in mls.where(c=>c.HOTID==hotelId).DefaultIfEmpty()
select new DTOHotMealsPrice
{
MEALSID = m.MEALSID,
MEALSNAME = m.MEALSNAME,
CHPRICE = mls1.CHPRICE,
PRICE = mls1.PRICE,
HOTID = mls1.HOTID
}).Distinct().ToList();

Join two linq queries on one key column to get one result set

Here I want to join the out put of the first query(one column) to the result of the 2nd query to get a one result set. How can I merge them.(CONCAT doesn't work as required. eg: var query2 = query.concat(query1);)
var query = (from PP in _db.paymentPlans
join APP in _db.Applications on PP.applicationID equals APP.ApplicationId
join C in _db.Courses on APP.courseID equals C.courseID
where PP.active == true && APP.agentID == agentID
orderby C.courseID ascending
group new {C,PP} by new {C.courseID} into totalRecievable
select new PdPpAppCourseModel
{
courseID = totalRecievable.Key.courseID,
totalAmount = totalRecievable.Sum(x => x.PP.totalAmount)
}).ToList();
var query1=(from PD in _db.paymentDetails
join PP in _db.paymentPlans on PD.paymentPlanID equals PP.paymentPlanID
join APP in _db.Applications on PP.applicationID equals APP.ApplicationId
join C in _db.Courses on APP.courseID equals C.courseID
where PP.active == true && APP.agentID == agentID
orderby C.courseID ascending
group new { C,PD } by new { C.courseID, C.cricosCode, C.courseName } into paymentsCourseWise
select new PdPpAppCourseModel
{
courseID = paymentsCourseWise.Key.courseID,
cricosCode = paymentsCourseWise.Key.cricosCode,
courseName = paymentsCourseWise.Key.courseName,
paidAmount = paymentsCourseWise.Sum(x => x.PD.paidAmount)
}).ToList();
You could join query1 and query like this
var result = (from q1 in query1
join q in query on q1.courseID = q.courseID
select new PdPpAppCourseModel
{
courseID = q1.Key.courseID,
cricosCode = q1.Key.cricosCode,
courseName = q1.Key.courseName,
paidAmount = q1.Sum(x => x.PD.paidAmount),
totalAmount = q.totalAmount
}).ToList();

How can i join two table in Linq and display the join to Data GridView?

I'm trying to join two tables and to display the Join result into GridView in WinForms, but something is going wrong...
it's not giving me Error message or something, Please help!!
my code :
var temp = teacherCmbBx.SelectedItem.ToString();
var temp2 = (from c in context.Teachers
where temp == c.FirstName
select c).ToList();
long num = temp2[0].ID;
var teacherGroup = (from t in context.Teachers
join g in context.Groups on t.ID equals g.TeacherID
where num == t.ID
select t);
teachergrpGridView.DataSource = teacherGroup;
string temp3 = (string)teachergrpGridView.Rows[rowNum].Cells[0].Value;
You are almost there. You are just missing .ToList()
var teacherGroup = (from t in context.Teachers
join g in context.Groups on t.ID equals g.TeacherID
where num == t.ID
select t).ToList();
teachergrpGridView.DataSource = teacherGroup;
var teacherGroup = from t in context.Teachers
join g in context.Groups on t.ID equals g.TeacherID
where num == t.ID
select new {
t.Id ,
g.Name,
t.xxxx
};

Categories