linq group by with count - linq

Im trying to write query in linq
Select UserId, UserNumber
FROM User
where UserNumber in
(Select UserNumber
FROM User
group by UserNumber
having Count(UserId) = 1)
Aby hints ?

var query = from u in User
group u by u.UserNumber into usergroup
where usergroup.Count() == 1
from item in usergroup
select new { item.UserId,item.UserNumber };

If subqueries are your thing, you could do it this way.
var subquery =
from u in User
group u by u.UserNumber into g
where g.Count() = 1
select g.Key;
var query =
from u in User
where subquery.Any(num => num == u.UserNumber)
select u;

Related

LINQ to SQL multiple tables left outer join w/condition in 'on' clause

SELECT u.username, COUNT(r.id)
FROM users u
LEFT JOIN userroles ur ON u.id = ur.userid
LEFT JOIN roles r ON ur.roleid = r.id AND r.name = 'Managers'
GROUP BY u.username
ORDER BY u.username
The goal is very simple, the above SQL runs fine, now I need to figure out how to convert it into LINQ code. I have the left joins working, the two things I don't know how to do is the count and the r.name = 'Managers'. Here is what I have so far, how do I finish it off?
var result =
from user in _context.Users
join userRole in _context.UserRoles on user.Id equals userRole.UserId into userUserRoleGroup
from u in userUserRoleGroup.DefaultIfEmpty()
join role in _context.Roles
on u.RoleId equals role.Id into roleUserRoleGroup
from r in roleUserRoleGroup.DefaultIfEmpty()
select new UserRole { Username = user.UserName, RoleName = r.Name };
You can do the count like this:
var count = from role in _context.Role
group role by role.UserId into groupedRoles
select new
{
RoleId = groupedRoles.Key,
Total = groupedRoles.Count()
}
and then you can join the variable "count" in your query.
It will have the property "Total" that is your count.

Issue with Group by clause in linq to sql

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),
};

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

Linq - Join results from 2 columns from same table

I would like to join results from a table, to sum up the results from a where condition on 2 different rows, as this code:
var a = (from o in _DB.Services
where (o.description.Contains(searchText) || o.nom.Contains(searchText))
orderby o.date
select new { results = ?????, id = ?????? }).Take(maxResults).ToList();
What can I put, in order to take into account the results=???? and id=???
Thanks
Based on your comment, can't you just do the following?
var a = (from o in _DB.Services
where (o.description.Contains(searchText) || o.nom.Contains(searchText))
orderby o.date
select new
{
results = o.description,
id = o.nom
})
.Take(maxResults)
.ToList();

LINQ count query returns a 1 instead of a 0

I have the following view:-
CREATE VIEW tbl_adjudicator_result_view
AS
SELECT a.adjudicator_id, sar.section_adjudicator_role_id, s.section_id, sdr.section_dance_role_id, d.dance_id, c.contact_id,
ro.round_id, r.result_id, c.title, c.first_name, c.last_name, d.name, r.value, ro.type
FROM tbl_adjudicator a
INNER JOIN tbl_section_adjudicator_role sar on sar.section_adjudicator_role2adjudicator = a.adjudicator_id
INNER JOIN tbl_section s on sar.section_adjudicator_role2section = s.section_id
INNER JOIN tbl_section_dance_role sdr on sdr.section_dance_role2section = s.section_id
INNER JOIN tbl_dance d on sdr.section_dance_role2dance = d.dance_id
INNER JOIN tbl_contact c on a.adjudicator2contact = c.contact_id
INNER JOIN tbl_round ro on ro.round2section = s.section_id
LEFT OUTER JOIN tbl_result r on r.result2adjudicator = a.adjudicator_id AND r.result2dance = d.dance_id
When I run the following query directly against the db I get 0 in the count column where there is no result
select adjudicator_id, first_name, COUNT(result_id)
from tbl_adjudicator_result_view arv
where arv.round_id = 16
group by adjudicator_id, first_name
However when I use LINQ query I always get 1 in the Count Column
var query = from arv in db.AdjudicatorResultViews
where arv.round_id == id
group arv by new { arv.adjudicator_id, arv.first_name} into grp
select new AdjudicatorResultViewGroupedByDance
{
AdjudicatorId = grp.Key.adjudicator_id,
FirstName = grp.Key.first_name,
Count = grp.Select(p => p.result_id).Distinct().Count()
};
What do I need to change in the View / Linq query.
You're not doing the same thing in the LINQ query as in the SQL. COUNT(result_id) does not count distinct values of result_id - it counts non-null values.
Try this instead:
Count = grp.Select(p => p.result_id).Where(x => x != null).Count()
The point is: you're grouping your data in the LINQ query - and you'll always get at least one group.
That group's Count may be 0 - but the count of groups will be 1.

Resources