-1
I spent the day looking for how LINQ works and tried to use in a little project I’m using to study, after a long time trying the code using LINQ became like this:
for (var dia = comeco.Date; dia.Date <= fim.Date; dia = dia.AddDays(1))
{
if((from Hospedagem hospedagem in db.Hospedagens.ToList()
where (hospedagem.DataEntrada <= dia && dia <= hospedagem.DataSaida)
select hospedagem) != null)
{
hospedagens.Concat((from Hospedagem hospedagem in db.Hospedagens.ToList()
where (hospedagem.DataEntrada <= dia && dia <= hospedagem.DataSaida)
select hospedagem).ToList());
}
}
if (hospedagens != null)
{
hospedagens = hospedagens.GroupBy(x => x.HospedagemID).Select(g => g.First()).ToList();
}
But it didn’t work, so I did using foreach, so it worked:
List<Hospedagem> lista = db.Hospedagens.ToList();
List<Hospedagem> hospedagens = new List<Hospedagem>();
for (var dia = comeco.Date; dia.Date <= fim.Date; dia = dia.AddDays(1))
{
foreach (Hospedagem h in lista)
{
if (h.DataEntrada <= dia && dia <= h.DataSaida)
{
hospedagens.Add(h);
}
}
}
if (hospedagens != null)
{
hospedagens = hospedagens.GroupBy(x => x.HospedagemID).Select(g => g.First()).ToList();
}
wanted to understand why the first code didn’t work and how I could fix his problems.
Are you using EF? Are you taking the DB data, turning a list and making the selection? If that’s what you do in LINQ it looks better. Not that it is good, the right is to use LINQ to generate an SQL query in the database and bring already filtered, but then the code has to be totally different, and does not have enough information to help.
– Maniero
yes I am using EF, the idea is to take from the hosting class (a class that relates a client to a room and has date and exit properties) and with two date values passed by parameter (beginning and end) make the selection of only the hosts that are within that time period.
– Pedro Santos