Search code examples
sqllambdalinqpad

How to translate what I do with the [Confirmed / Total] field in this query to lambda? with CAST


I'm trying to get all the users that have confirmed an Event and the following query shows how it should look

select us.ServiceId, s.Image, s.Title, s.CreatedTimestamp, (cast(count(us.Answer) as varchar(10))) + 
'/' + (cast((select count(Id) from Users) as varchar(10))) [Confirmed / Total]
from Services s inner join UserServices us on s.Id = us.ServiceId
where us.ServiceId = '5cf37da7-e7ba-4652-8526-96b3ad19fd13'
group by us.ServiceId, s.Image, s.Title, s.CreatedTimestamp

The result:

resultQuery

but I can only get users who have been confirmed, I want to get users total too.

I did a lambda with the most fields, except the users total:

Services.Join(UserServices, s => s.Id, us => us.ServiceId, (s, us) => new { s,us })
.Where(w => (w.us.ServiceId == "5cf37da7-e7ba-4652-8526-96b3ad19fd13"))
.GroupBy(gb => new  
     {
        ServiceId = gb.us.ServiceId, 
        Image = gb.s.Image, 
        Title = gb.s.Title, 
        CreatedTimestamp = gb.s.CreatedTimestamp,
        ConfirmedTotal = gb.us.Answer
     }, gb => new { us = gb.us, s = gb.s })
.Select(sl => new  
     {
        ServiceId = sl.Key.ServiceId, 
        Image = sl.Key.Image, 
        Title = sl.Key.Title, 
        CreatedTimestamp = sl.Key.CreatedTimestamp,
        ConfirmedTotal = sl.Count(x => x.us.Answer)
     })

The result:

resultQuery2

So, how to translate that or is there some way to do that?


Solution

  • I tried this and it worked:

    Services.Join(UserServices, s => s.Id, us => us.ServiceId, (s, us) => new { s,us })
    .Where(w => (w.s.ServiceTypeId == "efb6fd56-45be-4402-a960-ed93bcbeea79"))
    .GroupBy(gb => new  
         {
            ServiceTypeId = gb.us.ServiceId, 
            Image = gb.s.Image, 
            Title = gb.s.Title, 
            CreatedTimestamp = gb.s.CreatedTimestamp,
            ConfirmedTotal = string.Concat(gb.us.Answer.ToString(), " / ", db.Users.Select(s => s.Id).Count().ToString())
    })
    .Select(s => new  
         {
            ServiceId = s.Key.ServiceTypeId, 
            Image = s.Key.Image, 
            Title = s.Key.Title, 
            CreatedTimestamp = s.Key.CreatedTimestamp,
            ConfirmedTotal = string.Concat(s.Count(x => x.us.Answer).ToString(), " / ", db.Users.Select(s2 => s2.Id).Count().ToString())
         })