How to do this in LINQ?

-1

I spent the day looking for how LINQ works and I tried to use it in a project I'm using to study, after a long time trying the code using LINQ it looks 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 did not 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();
        }

I wanted to understand why the first code did not work and how I could fix it.

    
asked by anonymous 24.01.2018 / 21:45

1 answer

0

If you want only what is inside the for, it would look like this:

List<Hospedagem> hospedagens = new List<Hospedagem>();

for (var dia = comeco.Date; dia.Date <= fim.Date; dia = dia.AddDays(1))
{
    hospedagens.AddRange(from h in db.Hospedagens where h.DataEntrada <= dia && dia <= h.DataSaida select h);
}

if (hospedagens != null)
{
    hospedagens = hospedagens.GroupBy(x => x.HospedagemID).Select(g => g.First()).ToList();
}

Your code does not work because concat does not modify the list, it returns a new one, in your case it would be better to use AddRange.

    
24.01.2018 / 23:24