Bring three possible results with Lambda

1

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

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

How do I bring three possible results?

    
asked by anonymous 05.05.2014 / 20:52

2 answers

3

You can use LINQ syntax to make it easier to create a value that contains the difference, using let , and then use that calculated value in select to return the values you want, using the ternary conditional operator (ie 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();
    
05.05.2014 / 21:01
2

I think this 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 remember to change new DateTime (2014, 5, 5) by its default date.

Explaining:

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

    
05.05.2014 / 21:01