Getting all values on Lambda

Asked

Viewed 72 times

3

My code has the following structure:

var a = ViewData["a"];
var b = ViewData["b"];
var c = ViewData["c"];
var d = ViewData["d"]:
foreach(var x in ObjetoE).where(x=> x.A == a && x.B == b && x.C == c && x.D == d){
// Faz alguma ação
}

In case, man ObjetoE would be more or less like this:

public class ObjetoE
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    public string D { get; set; }
}

What happens is that the values defined for the variables a,b,c and d are dynamically assigned, in this case, by the ViewData, may be null. In this case what I would like to understand is if there is something that could take all if a variable is null, like a * of a query. Because it is impossible to work as conditionals validating whether the variable is null and generating several foreach the basis of each condition.

  • The problem seems to be interesting, but I do not understand what you are wanting. Maybe it is purposeful but this code does not make sense.

  • @I edited it, now it might make a little more sense. But basically my question boils down to the fact that I need to have X options in my lambda, but some may come null and the same should be ignored. I have no intention to check condition and apply various foreach validating whether the input variables are null

1 answer

3


You can do several ifs and filter the IEnumerable that at the end will be iterated into a single foreach, it is not necessary to place a foreach for each if:

var items = ObjetoE as IEnumerable<TipoDoElemento>;
if (a != null)
    items = items.Where(x=> x.V1 == a);
if (b != null)
    items = items.Where(x=> x.V2 == b);
if (c != null)
    items = items.Where(x=> x.V3 == c);
if (d != null)
    items = items.Where(x=> x.V4 == d);

foreach(var x in items)
{
    // Faz alguma ação
}

Browser other questions tagged

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