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?
a source to share
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");
a source to share
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;
}
}
);
a source to share