views:

603

answers:

1

Hi !

I've written a code for filtering items in ComboBox:

My question is, how would you do that?

I think that this solution with reflection could be very slow..

ICollectionView view = CollectionViewSource.GetDefaultView(newValue);
view.Filter += this.FilterPredicate;


private bool FilterPredicate(object value)
{            
    if (value == null)
        return false;

    if (String.IsNullOrEmpty(SearchedText))
        return true;            

    int index = value.ToString().IndexOf(
        SearchedText,
        0,
        StringComparison.InvariantCultureIgnoreCase);

    if ( index > -1) return true;

    return FindInProperties(new string[] { "Property1", "Property2" }, value, SearchedText);
}

private bool FindInProperties(string[] properties, object value, string txtToFind)
{
    PropertyInfo info = null;
    for (int i = 0; i < properties.Length; i++)
    {
        info = value.GetType().GetProperty(properties[i]);
        if (info == null) continue;

        object s  = info.GetValue(value, null);
        if (s == null) continue;

        int index = s.ToString().IndexOf(
            txtToFind,
            0,
            StringComparison.InvariantCultureIgnoreCase);

        if (index > -1) return true;
    }
    return false;
}
+1  A: 

Why not just this:

ICollectionView view = CollectionViewSource.GetDefaultView(newValue);
IEqualityComparer<String> comparer = StringComparer.InvariantCultureIgnoreCase;
view.Filter = o => { 
                     Person p = o as Person; 
                     return p.FirstName.Contains(SearchedText, comparer) 
                            || p.LastName.Contains(SearchedText, comparer); 
                   }

Do you need to search properties dynamically?

codekaizen
I don't know what the underlying ItemSource is going to be. It has to work for every object
PaN1C_Showt1Me
The user of that Control must be given a possibility to choose how to search.
PaN1C_Showt1Me
Well, then, yea, reflection is about the only way you are going to accomplish this. I think you'll probably be ok, performance-wise, unless you are dealing with 10s or 100s of thousands of objects. You could implement IReflect on the type you are searching, and this might speed things up, if your measured performance is inadequate for user needs.
codekaizen