Delete a foreach and replace the result in a lambda expression in a method

Asked

Viewed 488 times

0

It’s pretty simple stuff. I have a method that takes a name inside a database and compares it with the parameter passed in the method and be equal, return it in the method, otherwise return a string.Empty. Turns out, I’m having a hard time doing it in a single row on my lambda. I did, but I had to fill a list on the lambda and then run the flat one foreach and compare item by item and know that in my expression, I can get on the same line and delete the foreach and the if. The break was not to continue after having found, I can have a large list and would generate unnecessary processing. See the method below:

private CotacaoContext contexto = new CotacaoContext();

        [AcceptVerbs("Get")]
        public string GetUsuarioLogin(string user)
        {
            var lista = new List<string>();
            string nomeusuario = string.Empty;
            contexto.Usuario.AsEnumerable().ToList().ForEach(u => lista.Add(u.NMUsuario.ToList().ToString()));
            foreach (var l in lista)
            {
                if (l == user)
                {
                    nomeusuario = user;
                    break;
                }
            }
            return nomeusuario;
        }
    }

1 answer

2


You can do it using the method Any().

Some important points to note in your code:

  • No need to call AsEnumerable() and then ToList(), you can use only one of the two methods;

  • Going even deeper, you don’t need to use either method because you don’t need to materialize all the items in the context to do this check, that’s waste. You can apply the method Any directly in context and prevent all table data from being recovered. This will cause the EF to generate a query making this check and that only the result of this query is returned to the application;

  • The excerpt u.NMUsuario.ToList().ToString() is unnecessary. Since u.NMUsuario be a string it is not necessary to convert it to list and then to string again, it is redundant.

private CotacaoContext contexto = new CotacaoContext();

[AcceptVerbs("Get")]
public string GetUsuarioLogin(string user)
{
    return contexto.Usuario.Any(u => u.NMUsuario == user) ? user : "";
}

You can see more about the method Any in: Difference between Any, Contains and Exists

  • LINQ, that piece ? user : "" makes all the difference. These Tostring(), Asenumerable() and etc, I put because I was making a mistake, but what was really missing was the "conclusion" of the expression, as I said. Thank you very much.

Browser other questions tagged

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