views:

41

answers:

3

Hi, I have some labels on my Page (e.g. Label1...Label100).

I don't want to loop through all Labels to check if Text property is = "" (or string.Empty, whatever), so this's my question - is it possible to use LINQ or Lambda Expression to get all "empty" labels ?

+7  A: 

You can find all the page controls through the Controls property

Page.Controls.OfType<Label>().Where(lbl => lbl.Text == "");

Note that this isn't recursive; i.e. if you have a PlaceHolder which has controls of its own, those will not be returned by Page.Controls.

David Hedlund
Good note on the fact that it only finds them in the top-level `Controls` collection.
Codesleuth
I like this LINQ thingie... All samples are quite lame, but this I can chew on, consume and make sense of.
ggonsalv
@ggonsalv: indeed. i don't know how i could even stand being a .net programmer pre linq/lambda
David Hedlund
@David Thanks for making us .Net 1.1 Neanderthals feel welcome... for next and while wend was regular staple. however doesn't the compiler eventually codes a loop and the rest is syntactic sugar?
ggonsalv
@ggonsalv: it is indeed - it doesn't enable you to do anything that you *couldn't* do before, it's just very convenient when the compiler codes the loops instead of me.
David Hedlund
@David True. Can't recount the number times I have written an endless loop, due to bad coding or incorrect boundary checking
ggonsalv
+2  A: 

You can make a "FindAllChildren" extension method that finds all controls recursively from some parent control (which could be the page), and have it return an IEnumerable<Control>. Then use a Linq query on that.

public static IEnumerable<Control> FindAllChildren(this Control control) 
{
    foreach(Control c in control.Controls) 
    {
        yield return c;
        foreach(control child in c.FindAllChildren() 
           yield return child;
    }
}

var allEmptyLabels = parent.FindAllChildren().OfType<Label>()
    .Where(l => l.Text == String.Empty);
driis
+1  A: 

Is that your label naming convention?

If so, this quick and dirty method could do:

List<Label> labels = new List();
for (int i = 0; i <= 100; i++)
{
    var label = (Label)Page.FindControl("Label" + i);
    if (label.Text != string.Empty)
        labels.Add(label);
}

// use labels collection here

No LINQ, or Lambdas, but it's another perspective for you.

Codesleuth
Yes, first time I used loop like that but I was wondering of other posibilities :)
Tony
Well, hopefully the labels aren't really named like that - unless they are getting automatically generated...
driis
@driis: He does say in the question they are named like this ;)
Codesleuth