Where () with replacement () in the dictionary. Where (p => p.Key is T)

I have System.Collections.Generic.Dictionary<System.Web.UI.Control, object>

where all keys can be either type System.Web.UI.WebControls.HyperLink

or type System.Web.UI.WebControls.Label

.

I want to change the property Text

for each control. Since HyperLink doesn't implement (why ?!) ITextControl

, I need to explicitly specify the Label or HyperLink:

Dictionary<Control,object> dic = ..

dic
  .Where(p => p.Key is HyperLink)
  .ForEach(c => ((HyperLink)c).Text = "something")

dic
  .Where(p => p.Key is Label)
  .ForEach(c => ((Label)c).Text = "something")

      

Are there any workarounds for this approach?

+2


a source to share


6 answers


You can create a class derived from HyperLink and let your class inherit from ITextControl. It should be clear where to go from there ...



+3


a source


Slightly more elegant, but keeping the problem:



foreach (HyperLink c in dic.Keys.OfType<HyperLink>())
{
    c.Text = "something";
}

foreach (Label c in dic.Keys.OfType<Label>())
{
    c.Text = "something";
}

      

+5


a source


dic.ForEach(c => c.Key.GetType()
    .GetProperty("Text")
    .SetValue(c.Key, "Something",null));

      

A general hack may not be effective, but it should work.

EDIT: One more thing worth mentioning if you are using .Net 4 you can use duck printing:

dic.ForEach(kvp => ((dynamic)kvp.Key).Text = "Something");

      

+2


a source


This way looks uglier and more awkward, but at least you will only list the dictionary in one go:

dic
  .ForEach(
    c => {
      var clink = c as Hyperlink;
      if (clink != null) {
        clink.Text = "something";
        return;
      }

      var clabel = c as Label;
      if (clabel != null) {
        clabel.Text = "something";
        return;
      }
    }
  );

      

+2


a source


Same as Deng Tao - just styled for minimal clumsiness.

foreach(Control c in dic.Keys)
{
  HyperLink clink = c as Hyperlink; 
  if (clink != null)
  { 
    clink.Text = "something";
    continue;
  } 

  Label clabel = c as Label; 
  if (clabel != null)
  { 
    clabel.Text = "something";
    continue;
  } 
} 

      

+1


a source


If the text is not a Control property, it is clearer if you specify it in separate statements. I would not try to combine them simply because they both used the word "Text" to define a property.

0


a source







All Articles