123456789 123456789 - 3 months ago 9
C# Question

Search all properties that are string

Is there anyway to do change the "Where", in which it will automatic check all properties that contain a string instead of adding each property name manually?

items.Where(m => m.Property1.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0
|| m.Property2.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0
|| m.Property3.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0
|| m.Property4?.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0
|| m.Property5?.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0
|| m.Property6.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0
|| m.Property7?.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0
));


Thanks.

L.B L.B
Answer

I would write a code using reflection...

public bool MyContains(object instance, string word)
{
        return instance.GetType()
                .GetProperties()
                .Where(x => x.PropertyType == typeof(string))
                .Select(x => (string)x.GetValue(instance, null))
                .Where(x => x != null)
                .Any(x => x.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0);
}

Then your code would be

items.Where(m=>MyContains(m,word));