LINQ - 左连接,分组依据,总和,

时间:2017-09-04 21:15:13

标签: c# sql linq

我有这个sql代码:

select A.Recurso_Id, sum(case when B.cita_id is null then 0 else 1 end) as Total_Eventos,
a.Recurso_Nombre, a.Recurso_Email,a.Recurso_Activo
from Agenda_Recurso a left join Agenda_Cita  B
on A.Recurso_Id=B.Recurso_Id 
group by A.Recurso_Id,a.Recurso_Nombre, a.Recurso_Email,a.Recurso_Activo

而且,我需要转向LinQ,实际上我有这个代码:

List<Select> _ListaSelect = (from R in _LstRecursos
                               join C in _LstCitas
                               on R.Id equals C.Recurso_Id
                               group R by new {C.Recurso_Id, R.Nombre} into total
                               select new Select()
                               { 
                                   Cantidad_Eventos = total.Sum(R=> R.Id), 
                                   Recurso_Nombre= total.Max(R=> R.Nombre),
                                   Recurso_Email=total.Max(R=>R.Email),
                                   Recurso_Activo=total.Max(R=>R.Activo),
                                   Id_Recurso=total.Max(R=>R.Id)
                               }).ToList();

但是,它不起作用。你能救我吗?

1 个答案:

答案 0 :(得分:1)

我认为您的查询可以更简单,

试试这个

var citasbyRecurso =
            from r in recs
            join c in citas on r.RecursoID equals c.RecursoID into cleft
            select new
            {
                RecursoID = r.RecursoID,
                Name = r.Name,
                Email = r.Email,
                Count = cleft.Where(x=>x.RecursoID == 
                 r.RecursoID).Count(),
            };

这是完整的代码,因此您可以在控制台应用中运行此查询

class Program
{
    static void Main(string[] args)
    {
        var recs = new List<Recursos> {
new Recursos { Name = "Alex", Email = "A", RecursoID= 1 },
new Recursos { Name = "Juan", Email = "B", RecursoID= 2 },
new Recursos { Name = "Peter", Email = "C", RecursoID= 3 },
new Recursos { Name = "Julios", Email = "D", RecursoID= 4 },
new Recursos { Name = "Dennis", Email = "E", RecursoID= 5 },
new Recursos { Name = "Jhon", Email = "F", RecursoID= 6 },
};
        var citas = new List<Citas> {
new Citas { RecursoID= 1, CitaID = 1 },
new Citas { RecursoID= 1, CitaID = 2 },
new Citas { RecursoID= 2, CitaID = 3 },
};

        var citasbyRecurso =
            from r in recs
            join c in citas on r.RecursoID equals c.RecursoID into cleft
            select new
            {
                RecursoID = r.RecursoID,
                Name = r.Name,
                Email = r.Email,
                Count = cleft.Where(x=>x.RecursoID == r.RecursoID).Count(),
            };

        foreach (var item in citasbyRecurso)
        {
            Console.WriteLine(string.Format("{0} {1} {2} {3}", item.RecursoID,item.Name,item.Email, item.Count));
        }
        Console.ReadLine();
    }
}

class Recursos
{
    public int RecursoID;
    public string Name;
    public string Email;
}

class Citas
{
    public int RecursoID;
    public int CitaID;
}