我正在尝试实现一种方法,用于搜索某个搜索词的对象列表,然后返回这些对象。
到目前为止,如果搜索词包含在对象的任何字符串属性中,我就可以使其正常工作:
IEnumerableExtensions
public static IEnumerable<T> Search<T>(this IEnumerable<T> items, string search)
{
if (!string.IsNullOrEmpty(search))
items = items.Where(i => i.Contains(search));
return items;
}
对象扩展
public static bool Contains(this object inuputObject, string word)
{
return inuputObject.GetType()
.GetProperties()
.Where(x => x.PropertyType == typeof(string))
.Select(x => (string)x.GetValue(inuputObject, null))
.Where(x => x != null)
.Any(x => x.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0);
}
问题是,我正在搜索的对象都包含一个user对象列表,并且我想在搜索中包括这些用户的字符串属性。
我尝试了这个:
public static bool Contains(this object inuputObject, string word)
{
var result = false;
var type = inuputObject.GetType();
var properties = type.GetProperties();
foreach (var property in properties)
{
if (property.PropertyType == typeof(string) && property != null)
{
var propertyValue = (string)property.GetValue(inuputObject, null);
result = propertyValue.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) >= 0;
}
else
{
result = property.Contains(word);
}
if (result)
break;
}
return result;
}
但是我认为这是围绕我不感兴趣的属性进行迭代的,它会导致程序在VS中崩溃,并显示以下消息:
该应用程序处于中断模式
您的应用已进入中断状态,但由于所有线程都在执行外部代码(通常是系统代码或框架代码),因此没有要显示的代码。
我以前从未见过这样的错误,但是我怀疑它与运行到无限循环中的代码有关,因为它正在检查对象的属性,然后是这些属性的属性,等等-到哪里停止? ?
有人对我如何实现这一目标有任何建议吗?
子衿沉夜
神不在的星期二
相关分类