Bring three possible results with Lambda

Asked

Viewed 771 times

1

I need it in one expression to bring three possible outcomes. If date is up to 15dd, returns 1, if it is between 15 and 45 dd returns 2 and if it is larger than 45 returns 3. This is my lambda and the corresponding date field.

var resultado = webDB.T_Controle_Importacao.Where(ci => ci.DataTransacao....)

How I bring three possible results?

  • Just one more question. A lambda does not accept && or AND, I have to do as many Where as mine and(&&) right?

  • No problem using these operators.

  • Your question is not yet very clear to me. Could you explain better what these values are for (1, 2 and 3)? Could exemplify in what context these values will be used?

  • I need these values to indicate to the user the status of this cnpj. Are these three status(1,2 and 3).

2 answers

3


You can use LINQ syntax to make it easy to create a value that contains the difference, using let, and then use this calculated value in select to return the values you want, using the ternary conditional operator (i.e. cond ? a : b):

var resultado = (from ci in webDB.T_Controle_Importacao
                 let dd = EntityFunctions.DiffDays(DateTime.Now, ci.DataTransacao)
                 select dd >= 45 ? 3
                      : dd >= 15 ? 2
                      :            1
                ).ToList();
  • If this query does not return anything it is because webDB.T_Controle_Importacao has no item as there is no filter on this data.

  • Maybe it’s the lack of ToList, that made you think that no data was returned.

  • What ORM are you using? It’s the Entityframework?

  • Entity Framework, I just can’t guarantee to tell you the version, but it’s the 2012 version of VS

  • I edited to subtract dates using a DB function: EntityFunctions.DiffDays.

2

I think it works:

.Where(w => w.DataTransacao == (w.DataTransacao.AddDays(45) >= new DateTime(2014, 5, 5) ? 3 : w.DataTransacao.AddDays(15) <= new DateTime(2014, 5, 5) ? 1 : 2 ))

Just remembering to exchange new Datetime(2014, 5, 5) for its standard date.

Explaining:

If it is the longest date, already put 3, otherwise check if it is less than 15, put 1 or end is the middle clause with result 2.

  • Adddays does not work in this code context

Browser other questions tagged

You are not signed in. Login or sign up in order to post.