gerardo flores
gerardo flores

Reputation: 422

Cannot initialize TimeSpan with a collection initializer in linq query ¿Syntax error?

I build a ViewModel from a linq query to entities and then I do the following foreach:

_result.ForEach(t => t.horarioiniAFSP = (from U in model.AsistenciaCurso
                                          join T in model.Parametros
                                          on U.IdCurso equals T.ValorNumerico
                                          where U.UserId.Equals(t.UserId)
                                          && T.NombreParametro == "Modulo1"
                                          select new TimeSpan
                                          {
                                          U.HorarioInicio
                                          }).ToList());

However I can't get rid of the error: "Cannot initialize System.TimeSpan with a collection initalizer because it does not implement IEnumerable.

What is wrong? I suspect its a matter of syntax but I can't figure it out, formerly I did this:

_result.ForEach(t => t.horariofinAFSP = model.AsistenciaCurso.Where(u => u.UserId.Equals(t.UserId)).Select(x => x.HorarioFin).ToList());

Which is ok because I'm using linq Select, but then I tried to do the Join with lambdas like this:

_result.ForEach(t => t.horarioiniAFSP.AddRange(model.AsistenciaCurso.Where(u => u.UserId.Equals(t.UserId)).Join(model.Parametros, id => id.IdCurso, num => num.ValorNumerico, (id, num) => new TimeSpan { id.HorarioInicio })));

But that triggers the same error about not being able to initialize with a collection. I really don't have the time to google to much about this so that's why I'm asking this question. Any help will be greatly appreciated. Thanks in advance.

Upvotes: 0

Views: 83

Answers (1)

JLRishe
JLRishe

Reputation: 101730

(I know the solution has been found; posting an answer because nobody else has bothered to do so)

Like the error says, you can't initialize a TimeSpan with a collection initializer.

TimeSpan has four different constructors that you can choose from when creating a new one, but if you already have a timespan, then just use that:

from U in model.AsistenciaCurso
join T in model.Parametros
on U.IdCurso equals T.ValorNumerico
where U.UserId.Equals(t.UserId)
&& T.NombreParametro == "Modulo1"
select U.HorarioInicio

Upvotes: 1

Related Questions