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

Asked

Viewed 371 times

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 couldn’t find for the method Any(). And most give answers to LINQ.

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

1 answer

3


I’m not sure I understand your problem, but your code works perfectly.

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

If you are performing this as a filter for a list, you will get an error even.

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; }
}

Rotating the above example on dotNetFiddle it is possible to see that the result is True. That’s because there’s an answer to the Nome == "respostaUm". If you edit and remove the respostaUm and the respostaDois of the example, the result will be False.

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

  • Great answer! I actually asked the question conceptually because I couldn’t find examples for it. Now we have! Thank you! PS: I took the test, it works like I really thought!

  • Another thing is that you ended up differentiating and explaining .Where() and .Any(), that was very useful too! Thanks!

  • Hello @Thiagou.SperandioN., all right? So, by your question I assumed that the problem was more conceptual even, and that it might be having some kind of confusion, so I added both examples in my answer. I’m glad I could help

Browser other questions tagged

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