Lambda - how to use the || (OR) in an .Any ()

3

What would be the correct way to implement the line below in Lambda ?

ListaDeRespostasPossiveis.Any(x => x.Nome == "respostaUm" || x.Nome == "respostaDois")

I saw some examples in Stack Overflow in English, but I did not find it for the Any() method. And most give answers to LINQ.

The code is in a .cshtml file, and I wanted to keep the Lambda expression in a single line. How can I do it?

    
asked by anonymous 18.05.2017 / 01:33

1 answer

3

I do not know if I understand your problem well, but your code works perfectly.

Note that when you use .any () your answer will be bool , that is, true or false .

If you're doing this as if it were a filter for a list, you'll get a bug yourself.

See the example below:

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
          var ListaDeRespostasPossiveis = new List<Resposta>(){
                new Resposta() { id = 1, Nome = "respostaUm"},
                new Resposta() { id = 2, Nome = "respostaDois"},
                new Resposta() { id = 3, Nome = "respostatres"},
                new Resposta() { id = 4, Nome = "respostaQuatro"}
            };


        bool resppostasFiltro = ListaDeRespostasPossiveis.Any(x => x.Nome == 
                                    "respostaUm" || x.Nome == "respostaDois");

        //Como existe a respostaUm ou RespostaDois, o resultado aqui será True
        Console.WriteLine(resppostasFiltro);
    }
}

public class Resposta{
    public int id { get; set; }
    public string Nome { get; set; }
}

Running the example above in dotNetFiddle you can see that the result is True . This is because there is a response with Nome == "respostaUm" . If you edit and remove the respostaUm and respostaDois of the example, the result will be False .

Now, if you expect a list, use the .Where () instead of .Any() .

    
18.05.2017 / 01:53