搜索所有字符串属性
本文关键字:属性 字符串 搜索 | 更新日期: 2023-09-27 18:05:30
是否无论如何都要改变"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
));
谢谢。
我会用反射写代码…
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));
基于L.B的回答:我接受了他的回答
我把它分解成两个函数,因为不需要getwhere.
中每个实例的字符串属性
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)));