Receiving all values in Lambda

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 this case, my ObjetoE would be something 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 ViewData , being null . In case what I would like to understand is if there is something that could catch all if a variable is null, such as * of a query . For it becomes impossible to work as conditionals validating if the variable is null and generating several foreach on the basis of each condition.

    
asked by anonymous 14.04.2015 / 19:05

1 answer

3

You can make multiple if s and filter IEnumerable which in the end will be iterated in a single foreach , not having to 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
}
    
14.04.2015 / 19:21