Issue with Group by clause in linq to sql - linq

I want to make this query in linq to sql .
Please help. I am new to linq and having problem to with the group by clause .
Here is the sql query
select count(USERID), d.DEPTNAME from USERS u
join department d on u.DEPTID = d.DEPTID
group by u.DEPTID, d.DEPTNAME

A more direct translation would be like this:
var query =
from u in db.Users
join d in db.Departments on u.DeptId equals d.DeptId
group d by new { d.DeptId, d.DeptName } into g
select new
{
g.Key.DeptName,
Count = g.Count(),
};
Though I think it would be better off written like this:
// looks like we're counting users in each department
var query =
from d in db.Departments
select new
{
d.DeptName,
Count = db.Users.Count(u => u.DeptId == d.DeptId),
};

Related

How to use MAX in subquery in LINQ

I am trying to write my first query in LINQ
This is my SQL query
SELECT P.id,PS.Id,P.CPersonName
,PS.StartDate FROM Provider P
LEFT OUTER JOIN ProviderSubscription PS ON
P.id=PS.providerID
AND PS.Id=(SELECT max(id)from ProviderSubscription where
providerSubscription.ProviderId=Provider.id)
And so far i wrote this LINQ.
var query = (from p in db.Providers
join ps in db.ProviderSubscriptions on p.Id
equals ps.ProviderId
select new ViewModel
{
providerid = p.Id,
providername = p.ProviderName,
subscriptiondate = ps.ExpiryDate,
}).ToList();
I am unable to add this part in my LINQ.
AND PS.Id=(SELECT max(id)from ProviderSubscription where
providerSubscription.ProviderId=Provider.id)
I don't think you need a subquery, when you're doing a join with same tables and with same conditions then there is NO need to again write an inner query with same tables. Below query should return same result:
var query = (from p in db.Providers
join ps in db.ProviderSubscriptions on p.Id equals ps.ProviderId
where ps.Contains(ps.Max(u=>u.id))
select new ViewModel
{
providerid = p.Id,
providername = p.ProviderName,
subscriptiondate = ps.ExpiryDate,
}).ToList();

Linq query joining with a subquery

I am trying to reproduce a SQL query using a LINQ to Entities query. The following SQL works fine, I just don't see how to do it in LINQ. I have tried for a few hours today but I'm just missing something.
SELECT
h.ReqID,
rs.RoutingSection
FROM ReqHeader h
JOIN ReqRoutings rr ON rr.ReqRoutingID = (SELECT TOP 1 r1.ReqRoutingID
FROM ReqRoutings r1
WHERE r1.ReqID = h.ReqID
ORDER BY r1.ReqRoutingID desc)
JOIN ReqRoutingSections rs ON rs.RoutingSectionID = rr.RoutingSectionID
Edit***
I was able to get this working after looking at other examples including the one provided her by Miki. Here is the code that works for me:
First I created a query called route to hold the top record I needed to join to
var route = (from rr in context.ReqRoutings
where rr.ReqID == id
orderby rr.ID descending
select rr).Take(1);
I was then able to join to my requisitions table and the ReqRoutings lookup table
var header = (from h in context.ReqHeaders
join r in route on h.ID equals r.ReqID
join rs in context.ReqRoutingSections on r.RoutingSectionID equals rs.ID
where h.ID == id
select {ReqID = h.ID,
RoutingSection = rs.RoutingSection}
I am using Northwnd sample database
Customers,Orders,Employees table
Here I am getting top 1 order group by customer and order's employeeid
Please let me know If this is matching with your requirement or not
var ord = from o in NDC.Orders
orderby o.OrderID descending
group o by o.CustomerID into g
select new {CustomerID=g.Key,Order=g.OrderByDescending(s=>s.OrderID).First() };
var res1 = from o in ord
join emp in NDC.Employees
on o.Order.EmployeeID equals emp.EmployeeID into oemp
select new {Order=o.Order,employee=oemp };
Response.Write(res1.ToList().Count);
foreach (var order in res1)
{
Response.Write(order.Order.CustomerID + "," +
order.Order.OrderID + ","+
order.Order.EmployeeID+"<br/>");
}
// Above code is working .I have tried to convert your query to linq and replace your datacontext name with 'NDC'
var ord = from rr in NDC.ReqRoutings
orderby rr.ReqRoutingID descending
group rr by rr.ReqID into g
select new
{
ReqID = g.Key,
ReqRoutings = g.OrderByDescending(s => s.ReqRoutingID).First()
};
var res1 = from o in ord
join emp in NDC.ReqRoutingSections on o.ReqRoutings.RoutingSectionID
equals emp.RoutingSectionID into oemp
select new { ReqRoutings = o.ReqRoutings, employee = oemp };
Response.Write(res1.ToList().Count);
foreach (var order in res1)
{
Response.Write(order.ReqRoutings.ReqID + "," +
order.ReqRoutings.ReqRoutingID + "," +
order.ReqRoutings.RoutingSectionID + "<br/>");
}
Please let know if it is help you or not

Join statement in Linq to Sql

I need to write Join statment after writing query in linq
example :
var Query = (from Tab in Db.Employees
select Tab)
as i have some cases to perform join operation so
i need to do it on this Query Query.Join(Join with another Table like Department); I need the Syntax
if (DeptID != -1){ Query.Join(Join with table Department where FkDeptID = DeptID); }
Consider the usage of join in the LINQ 'query syntax':
from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}
Something like this?
var results = (from q in Query
join m in myList on q.SomeID = m.SomeID
select unknown);
Try using this query:
var Query =
from e in Db.Employees
join d in Db.Departments on e.FkDeptID equals d.DeptID into departments
select new
{
Employee = e,
Department = departments.SingleOrDefault(),
};
This works assuming that when e.FkDeptID == -1 that there is no record in the Departments table and in that case Department would be assigned null.
You should never have more than one department for an employee so I've used SingleOrDefault rather than FirstOrDefault.

Group by, Sum, Join in Linq

I have this simple sql query:
select c.LastName, Sum(b.Debit)- Sum(b.Credit) as OpenBalance from Balance as b
inner join Job as j on (b.Job = j.ID)
inner join Client as c on (j.Client = c.ID)
Group By c.LastName
and I am trying to convert it to work in linq like this:
from b in Balance
join j in Job on b.Job equals j.ID
join c in Client on j.Client equals c.ID
group b by new { c.LastName } into g
select new {
Name = c.Lastname,
OpenBalance = g.Sum(t1 => t1.Credit)
}
but when I try to run it in LINQPad I get the following message:
The name 'c' does not exist in the
current context
and it highlights c.Lastname in select new statement.
Any help on this will be greatly appreciated.
Thank you.
Well, you've grouped b by c.LastName. So after the grouping operation, you're dealing with g which is a grouping with the element type being the type of b, and the key type being the type of c.LastName. It could well be that all you need is:
select new {
Name = g.Key,
OpenBalance = g.Sum(t1 => t1.Credit)
}
... but if you need to get at any other aspects of c, you'll need to change your grouping expression.

linq join table with collection

I have a collection that I'm gathering from a linq query and I'd like to use that collection as a join for another query. How do I do that?
Thanks
LINQ 101 Samples
Copied LINQ statements from here
string[] categories = new string[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
List<Product> products = GetProductList();
var q =
from c in categories
join p in products on c equals p.Category
select new { Category = c, p.ProductName };
foreach (var v in q)
{
Console.WriteLine(v.ProductName + ": " + v.Category);
}
Try this
var query2 = from c in db.YourTable
join q in query1 on c.Id equals q.Id
select c;
Where query1 wats your first collection that originated from a linq query.
You should be able to do this:
List<Product> products = GetProductList(); //collection
var q = from c in categories
join p in products on c equals p.Category into ps
select new { Category = c, Products = ps };
Below is a Linq query I wrote that does exactly that. This is a Linq to SQL query that joins in a local collection.
int[] keyList = new int[] { 7064, 7065, 6242 };
var query = (from child in ETAModule
join parent in ETA on child.ExpID equals parent.ExpID
where child.ID >= 65490442
where keyList.Contains(child.ExpID)
orderby child.ID
select new { EtaModule = child, Eta = parent });
...not a whole lot of information provided, but here is a very simple example.
var firstCollection = List<YourClassNameHere>(); // this is your pre-existing collection
var results = from o in firstCollection
join i in SomeOtherCollection on o.JoinField equals i.JoinField
select i; // or whatever you like

Resources