Reputation: 2899
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.
Upvotes: 1
Views: 1507
Reputation: 2899
Based on L.B answer: I accepted his answer
I broke it down into two functions because there is no need to get the string properties for each instances in the where.
public static class ObjectUtils
{
public static IEnumerable<PropertyInfo> GetPropertiesByType<TEntity>(TEntity entity, Type type)
{
return entity.GetType().GetProperties().Where(p => p.PropertyType == type);
}
public static bool CheckAllStringProperties<TEntity>(TEntity instance, IEnumerable<PropertyInfo> stringProperties, string word)
{
return stringProperties.Select(x => (string)x.GetValue(instance, null))
.Where(x => x != null)
.Any(x => x.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0);
}
}
Then
var stringProperties = ObjectUtils.GetPropertiesByType(new Item(), typeof(string));
items.Where(x => ObjectUtils.CheckAllStringProperties(x, stringProperties, word)));
Upvotes: 1
Reputation: 116108
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));
Upvotes: 4