Only with LINQ
is not possible, you can even do with T-SQL
, either using LEAD
/ LAG
, or using% recursive%.
But only with C #, you can create a Dictionary, then check if there is at least one Measurement in a given period of months.
public static class Util
{
private static Dictionary<DateTime, int> qtdMedicoesMes = CountMedicoes();
private static Dictionary<DateTime, int> CountMedicoes()
{
List<Medicao> medicoes = Banco.CarregarListaMedicoes();
return (
from medicao in medicoes
group medicao by medicao.AddDays(medicao.Day * -1).AddDays(1).Today into medicoesMes
select new {
Mes = medicoesMes.Key,
Medicoes = medicoesMes.ToList()
}
).ToDictionary(qtdMedicaoMes => qtdMedicaoMes.Mes, qtdMedicaoMes => qtdMedicaoMes.Quantidade);
}
public static bool HasMedicao (DateTime dataInicial, int qtdMeses)
{
for (var mes = dataInicial; mes < dataInicial.AddMonths(qtdMeses); mes = mes.AddMonths(1))
{
if (countMedicoes.ContainsKey(mes) && countMedicoes[mes] > 0)
{
return true;
}
}
return false;
}
}
Then you will need to make the following calls:
public class MedicaoController : ApiController
{
public bool Verificar(int mes, int ano)
{
var mes = new DateTime(ano, mes, 1);
dynamic obj = new ExpandoObject();
obj.AusenciaMedicaoUmMes = !Util.HasMedicao(mes, 1);
obj.AusenciaMedicaoDoisMeses = !Util.HasMedicao(mes, 2);
obj.PossuiMedicaoTresMeses = Util.HasMedicao(mes, 3);
obj.AusenciaMedicaoQuatroMeses = !Util.HasMedicao(mes, 4);
return obj;
}
}