Is there any way to compare all received parameters?

Asked

Viewed 233 times

1

I have the following method

public Boolean Teste(String nome, String telefone, String...)
{
    if(!string.IsNullOrWhiteSpace(nome) || !string.IsNullOrWhiteSpace(telefone)...) {}
}

There is how to compare all these received values in a simpler way?

  • What do you want to do? There is a simple way, but it depends on your need

  • creating a model and using Dataannotations validation

  • 1

    @Leandroangelo And if it’s not ASP.NET MVC?

  • 1

    @LINQ Wow I swear I had read Action in place of Boolean

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

3


You have to walk a array received as parameter, using params, and sweep it all in a loop, making the if desiring.

If you don’t mind performance you can do with LINQ in a row.

Depending on what you wish to do allergy would be a little different.

If it really is to receive several fields of an object then it would be better to pass the object and do the sweep. Then you’d either have to do item by item or use reflection, which would make the code much slower, probably just to save typing, and it’s not simple to select fields, all would be used, unless with a slightly more complicated logic, you’d need to see if it pays off. It would need to generalize.

using static System.Console;
using System.Linq;

public class Program {
    public static void Main() {
        WriteLine(Teste("João", "048", "abc"));
        WriteLine(Teste("João", "048", "abc", ""));
        WriteLine(Teste("", "João", "048", "abc"));
        WriteLine(Teste("", null));
        WriteLine(Teste2("", null));
        WriteLine(Teste2("", null, "João", "048", "abc"));
    }
    public static bool Teste(params string[] textos) {
        foreach (var item in textos) if (!string.IsNullOrWhiteSpace(item)) return true;
        return false;
    }
    public static bool Teste2(params string[] textos) => textos.Any(item => !string.IsNullOrWhiteSpace(item));
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

I took advantage and converted the code to C-style#.

  • Lambda Expressions wins!

Browser other questions tagged

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