无论如何都要更改" Where",它会自动检查包含字符串的所有属性,而不是手动添加每个属性名称?
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
));
感谢。
答案 0 :(得分:1)
我会用反射编写代码......
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);
}
然后你的代码将是
items.Where(m=>MyContains(m,word));
答案 1 :(得分:1)
基于L.B回答:我接受了他的回答
我将它分解为两个函数,因为没有必要得到它 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);
}
}
然后
var stringProperties = ObjectUtils.GetPropertiesByType(new Item(), typeof(string));
items.Where(x => ObjectUtils.CheckAllStringProperties(x, stringProperties, word)));