如何在对象列表

时间:2018-04-19 23:53:21

标签: c# algorithm search

我试图实现一种搜索某个搜索词的对象列表然后返回这些对象的方法。

到目前为止,如果搜索字词包含在任何对象的字符串属性中,我已设法使其正常工作:

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;
}

ObjectExtensions

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个对象的列表,我希望在我的搜索中包含这些用户的字符串属性。< / p>

我试过了:

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中使用此消息崩溃:

  

应用程序处于中断模式

     

您的应用已进入中断状态,但没有要显示的代码,因为所有线程都在执行外部代码(通常是系统或框架代码)。

我之前从未见过这样的错误,但我怀疑它与运行到无限循环的代码有关,因为它检查对象的属性,然后检查这些属性的属性等等 - 那会停在哪里?

有没有人对如何实现这一目标有任何建议?

谢谢

2 个答案:

答案 0 :(得分:1)

您的递归调用检查def performAction(argument): if argument == 'I': insert() elif argument == 'U': update() elif argument == 'D': delete() elif argument == 'R': retrieve() elif argument == 'E': exit() else: print("Invalid Entry") 对象是否包含property,而不是原始对象上该属性的值是否包含该单词。

更改

word

result = property.Contains(word);

答案 1 :(得分:0)

我的最终解决方案看起来像这样

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");