Reputation: 3943
I have this code:
if (((Classes.ProductGroup)o).ToString().Contains(comboBox.Text))
return true;
else
return false;
Now I want not to specify the part Classes.ProductGroup
. I want to make it universal.
How can I replace the part Classes.ProductGroup
with a Type
object?
Type type = typeof(Classes.ProductGroup);
Something similar to this:
if (((type)o).ToString().Contains(comboBox.Text))
Is this possible?
Here is the complete method code:
private void FilterPGsinComboBox(object obj)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(new FilterPGsinComboBoxDelegate(this.FilterPGsinComboBox),obj);
return;
}
Type type = ((Dictionary<ComboBox, Type>)obj).First().Value;
ComboBox comboBox = ((Dictionary<ComboBox, Type>)obj).First().Key;
comboBox.IsDropDownOpen = true;
CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(comboBox.ItemsSource);
itemsViewOriginal.Filter = ((o) =>
{
if (String.IsNullOrEmpty(comboBox.Text))
return true;
else
{
if (((Classes.ProductGroup)o).ToString().Contains(comboBox.Text))
return true;
else
return false;
}
});
itemsViewOriginal.Refresh();
}
Upvotes: 0
Views: 66
Reputation: 35646
string ToString()
method is defined in the base Object
class. cast to concrete type is redundant.
string filter = comboBox.Text;
itemsViewOriginal.Filter = o => String.IsNullOrEmpty(filter) ||
o != null && o.ToString().Contains(filter);
Upvotes: 1
Reputation: 6155
You can use generics and build a method like
public bool ClassNameContainString<T>(string text) where T : class
{
var containsString = typeof(T).ToString().Contains(text);
return containsString;
}
If you want to make this method case insensitive change the logic to
var containsString = typeof(T).ToString().ToLower().Contains(text.ToLower());
Upvotes: 1