convert this into linq or lambda c# - c#

Can someone please help me convert this SQL to linq or lambda c#
select
count(s.ClassId) [StudentInClass], c.Name [Class], t.Name [teacher]
from
[dbo].[Students] s
inner join
class c on s.ClassId = c.Id
inner join Teacher t
on t.Id = c.TeacherId
group by
s.ClassId, c.Name, t.Name
so far this is what I have, and i am messing it up. I want to achieve the same results as in my sql query
SchoolEntities db = new SchoolEntities();
var StudentsByCourseId = from s in db.Students
join c in db.Classes on s.ClassId equals c.Id
join t in db.Teachers on c.TeacherId equals t.Id
group c by s.ClassId
into g
select g;
in SQL this is what my reults look like, it counts the students in a class by the teacher
StudentCount Class Teacher
1 Geography Teacher1
1 Biology Teacher1
2 Maths Teacher2

You can use an anonymous class to group by multiple properties.
var StudentsByCourseId = from s in db.Students
join c in db.Classes on s.ClassId equals c.Id
join t in db.Teachers on c.TeacherId equals t.Id
group s by new { s.ClassId, Class = c.Name, Teacher = t.Name }
into g
select new
{
StudentInClass = g.Count(),
g.Key.Class,
g.Key.Teacher,
};

Related

Need help on Linq-to-SQL query (maybe nested query?)

I am asking for your help regarding a linq query to SQL.
Here is a part of the diagram of my database: https://imgur.com/xFBUm3q
My problem is in the following relationship: tbl_607_bottle and tbl_607_gaz_reporting, I can have several reportings for a bottle but reporting can only have one bottle.
I do this request but it's not satisfying.
var GazReportingWizardViewModel =
(from gr in db.tbl_607_gaz_reporting
join a in db.tbl_607_actors on gr.FK_ID_actors equals a.id
join bo in db.tbl_607_bottle on gr.FK_ID_bottle equals bo.ID
join loc in db.tbl_607_location on bo.FK_ID_location equals loc.ID
join cc in db.tbl_607_conformity_certificate on bo.FK_ID_conformity_certificate equals cc.ID
join j in db.tbl_607_join_bottle_gaz on bo.ID equals j.FK_ID_bottle
join g in db.tbl_607_gaz on j.FK_ID_gaz equals g.ID
join od in db.tbl_607_order_details on g.FK_ID_order_details equals od.ID
where loc.ID == Process
select new GazReportingWizardViewModel
{
bottle_conti_number = bo.bottle_conti_number,
pressure_value = gr.pressure_value,
reporting_date = gr.reporting_date,
first_name = gr.tbl_607_actors.first_name,
last_name = gr.tbl_607_actors.last_name,
expiration_date = cc.expiration_date,
content = od.content_comments
}).Distinct()
.OrderBy(t => t.reporting_date)
.ToList();
I want the last report on each bottle but it return all reports on each bottle.
Would you have an idea of ​​the solution?
Thank you for your time
Thank you so much!
I persisted in trying to solve the problem in a single query when the solution was so simple.
var GazReportingWizardViewModel = (from gr in db.tbl_607_gaz_reporting
join a in db.tbl_607_actors on gr.FK_ID_actors equals a.id
join bo in db.tbl_607_bottle on gr.FK_ID_bottle equals bo.ID
join loc in db.tbl_607_location on bo.FK_ID_location equals loc.ID
join cc in db.tbl_607_conformity_certificate on bo.FK_ID_conformity_certificate equals cc.ID
join j in db.tbl_607_join_bottle_gaz on bo.ID equals j.FK_ID_bottle
join g in db.tbl_607_gaz on j.FK_ID_gaz equals g.ID
join od in db.tbl_607_order_details on g.FK_ID_order_details equals od.ID
where loc.ID == Process
select new GazReportingWizardViewModel
{
bottle_conti_number = bo.bottle_conti_number,
pressure_value = gr.pressure_value,
reporting_date = gr.reporting_date,
first_name = gr.tbl_607_actors.first_name,
last_name = gr.tbl_607_actors.last_name,
expiration_date = cc.expiration_date,
content = od.content_comments
}).ToList();
var res = from element in GazReportingWizardViewModel
group element by element.bottle_conti_number
into groups
select groups.OrderByDescending(p => p.reporting_date).First();

Can't access the fields of non-grouping tables in linq

I'm trying to join few tables using LINQ and retrieve a data set. But my problem is when I group the tables, I cannot access the fields of the non grouped tables in the LINQ query. here is my sample code block. Please help
var query = from sb in db.Surfboards
join csb in db.CustomerSurfBoards on sb.SurfBoardID equals csb.SurfBoardID
join c in db.Customers on csb.CustomerID equals c.CustomerID
where c.IsActive
group new { sb,csb} by new {sb.ID, csb.ComponentId} into g
select new ReportModel()
{
ReceivedDate = g.First().Name,
Number = c.First().Number <------- this cannot be accessed
}
what I'm trying to achieve is something like this
select sb.Id, max(c.Number), cbs.Id from Surfboards as sb
inner join CustomerSurfBoards as cbs on sb.SurfBoardID = csb.SurfBoardID
inner join Customers as c on csb.CustomerID = c.CustomerID
group by sb.Id, csb.ComponentId
Try this:
var query = from sb in db.Surfboards
join csb in db.CustomerSurfBoards on sb.SurfBoardID equals csb.SurfBoardID
join c in db.Customers on csb.CustomerID equals c.CustomerID
where c.IsActive
select new {sb.id, c.number, cbs.componentid} into tmp
from t in tmp
group t by new {t.ID, t.ComponentId} into g
select new
{
g.Key.id, g.Key.componentid, number = g.Select(n=>n.number).OrderByDescending().FirstOrDefault()
}

Convert SQL into LINQ and Lambda

Please is somebody able to help me convert the following SQL query into LINQ
select p.Description,SUM(s.TotalArea) as TotalArea from Stands s
inner join ContractProducts cp on s.Id = cp.StandId
inner join Products p on cp.ProductId = p.Id
where s.EventId = 1
group by p.Description
Thanks in advance
Maybe something like this:
var result= (
from s in db.Stands
join cp in db.ContractProducts
on s.Id equals cp.StandId
join p in db.Products
on cp.ProductId equals p.Id
where s.EventId == 1
group p by p.Description into g
select new
{
Description=g.Key,
TotalArea = g.Sum (x =>x.TotalArea)
}
).ToList();
Where db is the linqdatacontext

Alternative to nesting when performing a left join and multiple inner joins

Consider the following fictitious scenario:
How would I go about getting a list of all the categories (distinct or otherwise, it doesn't matter) for each customer, even if a customer hasn't ordered any products?
Also assume that we don't have navigation properties, so we'll need to use manual joins.
This is my attempt which uses nesting:
var customerCategories = from c in context.Customers
join o in context.Orders on c.CustomerId equals o.CustomerId into orders
select new
{
CustomerName = c.Name,
Categories = (from o in orders
join p in context.Products on o.ProductId equals p.ProductId
join cat in context.Category on p.CategoryId equals cat.CategoryId
select cat)
};
Is there a different (possibly better way) to achieve the same outcome?
Alternative: Multiple Left (Group) Joins
var customerCategories = from customer in context.Customers
join o in context.Orders on customer.CustomerId equals o.CustomerId into orders
from order in orders.DefaultIfEmpty()
join p in context.Products on order.ProductId equals p.ProductId into products
from product in products.DefaultIfEmpty()
join cat in context.Categories on product.CategoryId equals cat.CategoryId into categories
select new
{
CustomerName = c.Name,
Categories = categories
};
I recreated your table structure and added some data so that I could get a better idea what you were trying to do. I found a couple of ways to accomplish what you want but I'm just going to add this method. I think it's the most concise and I think it's pretty clear.
Code
var summaries = Customers.GroupJoin(Orders,
cst => cst.Id,
ord => ord.CustomerId,
(cst, ord) => new { Customer = cst, Orders = ord.DefaultIfEmpty() })
.SelectMany(c => c.Orders.Select(o => new
{
CustomerId = c.Customer.Id,
CustomerName = c.Customer.Name,
Categories = Categories.Where(cat => cat.Id == c.Customer.Id)
}));
Output
Table Structure
Table Data
If you need all categories couldn't you just:
Categories = (from c in context.Category
select cat)

SQL Query selecting where there are more than 3 distinct

I am having problems with a SQL query, i need a list of consumers having purchased at least 3 different products whose suppliers are from a certain city (Lets say new york).
Tabels Columns:
Tb_Consumer..........Con_ID(PK), Name, City
Tb_Supplier.............Supp_ID(PK), Name, City
Tb_Transactions.....Tran_ID(PK), Supp_ID(FK), Con_ID(FK), PROD_ID(FK)
Tb_Products............Prod(ID(PK), Name
What i have so far:
var query8Result = (from c in context.Tb_Consumer
join t in context.Tb_Transactions on c.Con_ID equals t.Con_ID
join s in context.Tb_Supplier on t.Supp_ID equals s.Supp_ID
join p in context.Tb_Product on t.Prod_ID equals p.Prod_ID
where s.City == "New York"
select new { Name = c.Name }).Distinct();
I think you need a few Group-by's
var query8Result = (from c in context.Tb_Consumer
join t in context.Tb_Transactions on c.Con_ID equals t.Con_ID
join s in context.Tb_Supplier on t.Supp_ID equals s.Supp_ID
join p in context.Tb_Product on t.Prod_ID equals p.Prod_ID
where s.City == "New York"
group c by new { c.Name, t.Prod_ID } into customerProducts
group customerProducts by new { customerProducts.Key.Name } into customers
where customers.Count() > 3
select g.Key);
Sorry if this isn't 100% correct - It's a little hard to test this...

Categories