Filter on where the largest date with LINQ

3

As I pass in the where of this linq to max datatransaction, ie, I want to bring the result but for the greater date.

var resultado = (from ci in webDB.T_Controle_Importacao
                             where ci.CNPJ == cnpj
                             let dd = EntityFunctions.DiffDays(DateTime.Now, ci.DataTransacao)
                             select dd >= 45 ? 3
                                  : dd >= 15 ? 2
                                  : 1).Take(1);
    
asked by anonymous 06.05.2014 / 01:13

2 answers

2

You can sort the query so that the object with the largest date appears in the front, and then get the first record:

var resultado = (from ci in webDB.T_Controle_Importacao
                                 .OrderByDescending(ci => ci.DataTransacao)
                 where ci.CNPJ == cnpj
                 let dd = EntityFunctions.DiffDays(DateTime.Now, ci.DataTransacao)
                 select dd >= 45 ? 3
                      : dd >= 15 ? 2
                      :            1
                )
                .Take(1);

Note that doing this is it is recommended that you have an index in the column that stores the date in the database , so sorting is not slow.

    
06.05.2014 / 01:24
2

Order to bring the highest date with orderby field descending

var resultado = (from ci in webDB.T_Controle_Importacao
                    where ci.CNPJ == cnpj
                    let dd = EntityFunctions.DiffDays(DateTime.Now, ci.DataTransacao)
                    orderby ci.DataTransacao descending
                    select dd >= 45 ? 3 : dd >= 15 ? 2 : 1).Take(1);
    
06.05.2014 / 01:24