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

0

The thing is very simple indeed. I have a method that takes a name inside a database and compares with the parameter passed in the method and being is equal, return it in the method, otherwise return a string.Empty . It turns out, I'm having difficulty doing in a single line in my lambda. I did, but I had to fill a list in lambda and then loop through a foreach and compare item to item and I know that in my expression, I can get on the same line and delete foreach and if . break was not to continue after encountering, I may 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;
        }
    }
    
asked by anonymous 20.07.2017 / 14:52

1 answer

2

You can do this using the Any() method.

Some important things to note in your code:

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

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

  • The u.NMUsuario.ToList().ToString() excerpt is unnecessary. Since u.NMUsuario is 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 Any method at: Difference between Any, Contains and Exists

    
20.07.2017 / 14:58