I want to pick up all Sellers that aren't boss of a department.
How can I make this? In this query below, only the Sellers that are bosses of a department are picked up, I want the opposite of thereof.
My query:
var query = db.Sellers
.Join(db.Departments,
s => s.Id,
d => d.BossId,
(s, d) => new { Seller = s, Department = d })
.Where(a => a.Seller.Id == a.Department.BossId) ????
.Select(x => x.Seller).ToList();
In the "Where" part, I tried a => a.Seller.Id != a.Department.BossId, but it's wrong I have 3 sellers that aren't bosses.
I tried with this way too:
var listNonBoss = (from s in db.Sellers
join d in db.Departments on s.Id equals d.BossId
select s.Id).ToList();
I want just the opposite of these queries.
Sometimes it's easier to break it into multiple steps.
First, get the collection of all boss IDs:
var bossIDs = db.Departments.Select(x => x.BossId);
Then get all sellers whose IDs are not in that collection:
var listNonBoss = db.Sellers.Where(x => !bossIDs.Contains(x.Id)).ToList();
Join in your code will do an inner join, meaning it'll filter out sellers who don't have a boss.
To do the opposite you can do an outer join, and then remove the ones who have a boss. In fluent LINQ an outer join is done by doing a GroupJoin and then SelectMany.
Something like this:
var query = db.Sellers
.GroupJoin(db.Departments, s => s.Id, d => d.BossId, (s, d) => new { Seller = s, Department = d })
.SelectMany(x => x.d.DefaultIfEmpty(), (seller, department) => new { s.seller, department})
.Where(a => a.department.BossId == null)
.Select(x => x.Seller).ToList();
Or, using query syntax:
var listNonBoss = (from s in db.Sellers
join d in db.Departments on s.Id equals d.BossId into joinedTable
from jt in joinedTable.DefaultIfEmpty()
where jt.BossId == null
select s.Id).ToList();
Related
I have this query :
var ftr_dist = db.DIST_VIEW.Where(x => x.CITY == "Los Angeles");
var mst2 = db.TB_SERVICE.Where(x => x.ID == x.ID);
var trf2 = db.TYPE.Where(x => x.ID == x.ID);
var Data = (from ftr in ftr_dist
join mst in mst2 on ftr.CUSTOMER_ID equals mst.CUSTOMER_ID
join trf in trf2 on mst.TYPE_ID equals trf.ID
select new TypeObj { City = ftr.CITY, County = ftr.COUNTY, Type = trf.Type }
).OrderBy(i => i.City).ThenBy(i => i.County).ToList();
ftr_dist has about 72000 rows. mst2 has 1100000 rows and trf2 has 340 rows. But it takes too long to get Data. How can I make this query faster? Thanks.
you are essentially performing 4 different queries. Linq does take longer to query than sql strings... try this staying with Linq. Combine all of the queries into one.
I am a little confused in your lambda queries the (x => x.ID == x.ID). You may need to add this to the below
var data = from ftr in db.DIST_VIEW
join mst in db.TB_SERVICE on ftr.CUSTOMER_ID equals
mst.CUSTOMER_ID
join trf in db.TYPE on trf.TYPE_ID equals ftr.ID
where ftr.CITY == "Los Angeles"
select new TypeObj
{
City = ftr.City,
Country = ftr.County,
Type - trf.Type
}.OrderBy(i => i.City).ThenBy(i => i.County).ToList();
How do I convert this query to a LINQ query in Entity Framework? I am a new programmer still in school
SELECT
studfirstname, studlastname, grade
FROM
students
INNER JOIN
Student_Schedules ON students.StudentID = Student_Schedules.StudentID
INNER JOIN
Classes ON Student_Schedules.ClassID = Classes.ClassID
INNER JOIN
Subjects ON Classes.SubjectID = Subjects.SubjectID
WHERE
SubjectName = 'Introduction to Art';
As you are new in Lambda and LINQ I tried in the following Lambda to be as descriptive as possible..... You can use the Long Aliases in short form also
student_schedules as ss OR studentsANDstudent_schedules as s_s_sch... Try this ...Hope this helps.... #Abdul Hameed
var filteredData = context.Students // your starting point
.Join(context.Student_Schedules, // the source table of the inner join
students => students.StudentID, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
student_schedules => student_schedules.StudentID),// the foreign key
(students, student_schedules) => new { students, student_schedules })
.Join(context.Classes,
classes => classes.ClassID,
studentsANDstudent_schedules => studentsANDstudent_schedules.student_schedules.ClassID),
(classes, studentsANDstudent_schedules) => new { classes, studentsANDstudent_schedules })
.Join(context.Subjects,
subjects => subjects.SubjectID,
studentsANDstudent_schedulesANDClasses => studentsANDstudent_schedulesANDClasses.classes.SubjectID),
(subjects, studentsANDstudent_schedulesANDClasses) => new { subjects, studentsANDstudent_schedulesANDClasses })
.Where(allMergedTables => allMergedTables.subjects.SubjectName == "Intoduction to Art").ToList();
And this is the shortened version of the above one...
var filteredData = context.Students
.Join(context.Student_Schedules, s => s.StudentID, sch => sch.StudentID),
(s, sch) => new { s, sch })
.Join(context.Classes, c => c.ClassID, s_sch => s_sch.sch.ClassID),
(c, s_sch) => new { c, s_sch })
.Join(context.Subjects, sj => sj.SubjectID, s_sch_c => s_sch_c.c.SubjectID),
(sj, s_sch_c) => new { sj, s_sch_c })
.Where(all => all.sj.SubjectName == "Intoduction to Art")
.ToList();
You can use LINQ syntax:
from student in context.Students
join schedule in context.Student_Schedules on student.StudentID equals schedule.StudentID
join #class in context.Classes on schedule.ClassID equals #class.ClassID
join subject in context.Subjects on #class.SubjectID equals subject.SubjectID
where subject.SubjectName == "Introduction to Art"
var students = context.Students.Include("Student_Schedules")
.Include("Classes")
.Include("Subjects").Where(s => s.Subjects.Contains("Intoduction to Art"));
Info -> https://msdn.microsoft.com/en-us/data/jj574232.aspx
I need to write following query in Linq to SQL but not sure what is the best way of doing, given it has two derived tables. Any suggestions.
SELECT A.ID
FROM
(
SELECT *
FROM Orders
WHERE ProductID = 5
) A
JOIN
(
SELECT CustomerID, MAX(Price) Price
FROM Orders
WHERE ProductID = 5
GROUP BY CustomerID
) B
ON A.CustomerID = B.CustomerID and A.Price = B.Price
var b = (
from o in db.Orders
where o.ProductID == 5
group o by o.CustomerID into og
select new {
CustomerID = og.Key
Price = Max(og.Price)
}
);
var a = (
from o in db.Orders
join p in b on new {a.CustomerID, a.Price} equals
new {b.CustomerID, b.Price}
where o.ProductID == 5
select a.ID
);
var r = a.ToString();
These two links are invaluable when forming things like this:
http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
http://msdn.microsoft.com/en-us/vstudio/bb688085
Can you simplify this with LINQ, especially if you use method syntax instead of query syntax.
orders.Where(o => o.ProductID == 5)
.GroupBy(o => o.CustomerID)
.SelectMany(g => g.Where(o => o.Price == g.Max(m => m.Price)));
My advice when writing LINQ, do not simply attempt to convert a SQL statement exactly. Think about the desired result and develop a solution designed for LINQ.
Something along these lines:
var result = from a in context.Orders
join b in (context.Orders.Where(o => o.ProductID == 5).GroupBy(o => o.CustomerID).Select(g => new { CustomerID = g.Key, Price = g.Max(o => o.Price)))
on new {a.CustomerID, a.Price} equals new {b.CustomerID, b.Price}
where a.ProductID == 5
select a.ID;
I have a simple LINQ lambda join query but I want to add a 3rd join with a where clause. How do I go about doing that?
Here's my single join query:
var myList = Companies
.Join(
Sectors,
comp => comp.Sector_code,
sect => sect.Sector_code,
(comp, sect) => new {Company = comp, Sector = sect} )
.Select( c => new {
c.Company.Equity_cusip,
c.Company.Company_name,
c.Company.Primary_exchange,
c.Company.Sector_code,
c.Sector.Description
});
I want to add the following SQL command to the above LINQ query and still maintain the projections:
SELECT
sector_code, industry_code
FROM
distribution_sector_industry
WHERE
service = 'numerical'
The 3rd join would be made with Sector table & Distribution_sector_industry on sector_code.
Thanks in advance.
Just a guess:
var myList = Companies
.Join(
Sectors,
comp => comp.Sector_code,
sect => sect.Sector_code,
(comp, sect) => new { Company = comp, Sector = sect })
.Join(
DistributionSectorIndustry.Where(dsi => dsi.Service == "numerical"),
cs => cs.Sector.Sector_code,
dsi => dsi.Sector_code,
(cs, dsi) => new { cs.Company, cs.Sector, IndustryCode = dsi.Industry_code })
.Select(c => new {
c.Company.Equity_cusip,
c.Company.Company_name,
c.Company.Primary_exchange,
c.Company.Sector_code,
c.Sector.Description,
c.IndustryCode
});
Okay, I can't see why you'd want to select sector_code when you already know it, but I think you want this:
var query = from company in Companies
join sector in Sectors
on company.SectorCode equals sector.SectorCode
join industry in DistributionSectorIndustry
on sector.SectorCode equals industry.SectorCode
where industry.Service == "numerical"
select new {
company.EquityCusip,
company.CompanyName,
company.PrimaryExchange,
company.SectorCode,
sector.Description,
industry.IndustryCode
};
Notes:
I've changed it into a query expression as that's a much more readable way of expressing a query like this.
Although the "where" clause comes after the join, assuming this is a LINQ to SQL or Entity Framework query, it shouldn't make any difference
I've lengthened the range variable names for clarity
I've converted your other names into conventional .NET names; you can do this too in your model
For 4 Tables
var query = CurrencyDeposits
.Join(Customers, cd => cd.CustomerId, cus => cus.Id, (cd, cus)
=> new { CurrencyDeposit = cd, Customer = cus })
.Join(Currencies, x => x.CurrencyDeposit.CurrencyId, cr => cr.Id, (x, cr)
=> new { x.CurrencyDeposit, x.Customer, Currency = cr })
.Join(Banks, x => x.CurrencyDeposit.BankId, bn => bn.Id, (x, bn)
=> new { x.CurrencyDeposit, x.Customer, x.Currency, Bank = bn})
.Select(s => new {
s.CurrencyDeposit.Id,
s.Customer.NameSurname,
s.Currency.Code,
s.Bank.BankName,
s.CurrencyDeposit.RequesCode
});
Try something like this...
var myList = ({from a in Companies
join b in Sectors on a.Sector_code equals b.Sector_code
join c in Distribution on b.distribution_code equals a.distribution_code
select new {...});
I am looking for a solution to have all the content of the table PART (by adding a right/left join I suppose) in the following LINQ query :
var query = (from p in db.PARTS
join oc in db.OUTPUT_CONTROLS on p.id equals oc.partid
join f in db.FCT on p.fct equals f.id
select new
{ p.id, p.plant, p.unit, p.type, p.num, f.name, oc.datetime, oc.ncr }
into x
group x by new
{ x.id, x.plant, x.unit, x.type, x.num, x.name }
into g
select new
{ g.Key.id, g.Key.plant, g.Key.unit, g.Key.type, g.Key.num, g.Key.name, startdate = g.Min(oc => oc.datetime), endate = g.Max(oc => oc.datetime), sumncr = g.Sum(oc => oc.ncr) })
.OrderByDescending(oc => oc.startdate);
Thanks
I found the solution on my own thanks to this post : LINQ Left Join And Right Join
The solution :
var query = (from p in db.PARTS
join oc in db.OUTPUT_CONTROLS on p.id equals oc.partid into joined
join f in db.FCT on p.fct equals f.id
from j in joined.DefaultIfEmpty()
select new
{ p.id, p.plant, p.unit, p.type, p.num, f.name, j.datetime, j.ncr } into x
group x by new { x.id, x.plant, x.unit, x.type, x.num, x.name } into g
select new { g.Key.id, g.Key.plant, g.Key.unit, g.Key.type, g.Key.num, g.Key.name, startdate = g.Min(oc => oc.datetime), endate = g.Max(oc => oc.datetime), sumncr = g.Sum(oc => oc.ncr) })
.OrderByDescending(oc => oc.startdate);
If you have a SQL where you see a join followed by a GroupJoin, consider using the LINQ GroupJoin.
Quite often you'll see this in situations where you want "Schools with their Students", "Customers with their Orders", "Zoos with their Animals"
It seems that you have 3 tables: Parts, OutputControls and Fcts.
Every Part has zero or more OutputControls, and every OutputControl belongs to exactly one Part, using foreign key PartId: a straightforward one-to-many relation
A Part has a foreign key FctId, that points to the Fct of the part.
You want (some properties of) the Parts, with their OutputControls and its Fct
var result = parts.GroupJoin(outputControls, // GroupJoin Parts and OutputControls
part => part.Id, // from every part take the Id
outputControl => outputControl.PartId, // from every outputControl take the PartId
// result selector: when these Ids match,
// use the part and all its matching outputControls to make one new object:
(part, outputControlsOfThisPart) => new
{
// select the part properties you plan to use:
Id = part.id,
Plant = part.plant,
Unit = part.unit
// the output controls of this part:
OutputControls = outputControlsOfThisPart.Select(outputControl => new
{
// again, select only the output control properties you plan to use
Id = outputControl.Id,
Name = outputControl.Name,
...
})
.ToList(),
// For the Fct, take the Fct with Id equal to Part.FctId
Fct = Fcts.Where(fct => fct.Id == part.Fct)
.Select(fct => new
{
// select only the Fct properties you plan to use
Id = fct.Id,
Name = fct.Name,
...
})
// expect only one such Fct
.FirstOrDefault(),
});