Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where() with Replace() in Dictionary.Where(p => p.Key is T)

I have a System.Collections.Generic.Dictionary<System.Web.UI.Control, object> where all keys can be either type of System.Web.UI.WebControls.HyperLink or type of System.Web.UI.WebControls.Label.

I want to change Text property of each control. Because HyperLink doesn't implement (why?!) ITextControl, I need to cast Label or HyperLink explicitly:

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 ways to workaround such approach?

like image 989
abatishchev Avatar asked Jan 22 '26 04:01

abatishchev


2 Answers

Slightly more elegant, but retaining the problem:

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

foreach (Label c in dic.Keys.OfType<Label>())
{
    c.Text = "something";
}
like image 189
dtb Avatar answered Jan 24 '26 20:01

dtb


You could create a class that derives from HyperLink and let your class inherit from ITextControl. Should be clear where to go from there...

like image 20
Stefan Egli Avatar answered Jan 24 '26 19:01

Stefan Egli