2 回答
TA贡献1828条经验 获得超3个赞
您的递归调用检查property
对象是否包含word
,而不是原始对象上该属性的值是否包含单词。
改变
result = property.Contains(word);
至
result = property.GetValue(inuputObject, null).Contains(word);
TA贡献1963条经验 获得超6个赞
我的最终解决方案如下所示
ObjectExtensions.cs
public static class ObjectExtensions
{
/// <summary>
/// Checks each string property of the given object to check if it contains the
/// search term. If any of those properties is a collection, we search that
/// collection using the the IEnumarableExtensions Search
/// </summary>
/// <param name="inputObject"></param>
/// <param name="term"></param>
/// <returns></returns>
public static bool Contains(this object inputObject, string term)
{
var result = false;
if (inputObject == null)
return result;
var properties = inputObject
.GetType()
.GetProperties();
foreach (var property in properties)
{
// First check if the object is a string (and ensure it is not null)
if (property != null && property.PropertyType == typeof(string))
{
var propertyValue = (string)property.GetValue(inputObject, null);
result = propertyValue == null
? false
: propertyValue.IndexOf(term,
StringComparison.CurrentCultureIgnoreCase) >= 0;
}
// Otherwise, check if its a collection (we need to do this after the string
// check, as a string is technically a IEnumerable type
else if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
{
result = ((IEnumerable<object>)property
.GetValue(inputObject, null))
.Search(term).Count() > 0;
}
else
{
var propertyValue = property.GetValue(inputObject, null);
result = propertyValue == null
? false
: propertyValue.ToString().Contains(term);
}
if (result)
break;
}
return result;
}
}
IEnumerableExtensions.cs
public static class IEnumerableExtensions
{
/// <summary>
/// Extension method that searches a list of generic objects' string properties
/// for the given search term using the 'Contains' object extension
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <param name="search"></param>
/// <returns></returns>
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;
}
}
用法
因此,要在对象集合中搜索某些字符串:
var list = new List<MyType>(){};
var results = list.Search("searchTerm");
- 2 回答
- 0 关注
- 190 浏览
添加回答
举报