且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用具有不同类型/类别列表的通用方法

更新时间:2022-10-16 17:59:22

我认为这就是您的意思:

 公共静态IList< T> SearchGridView< T>(IList< T>列表,字符串术语)
{
IList< PropertyInfo> properties = typeof(T).GetProperties();
var t = term.ToLower();
return list
.Where(item =>
properties
.Select(p => p.GetValue(item).ToString())
.Any (v => v.Contains(t)))
.ToList();
}


I am trying to build a search function for a List. This is quite simple, however I am trying to have a method, which can take Lists of different types. Take the following example to clearify the question:

The methods SearchGridViewCategorie and SearchGridViewMedewerker both are methods to search the List if it contains the search term.

public static void SearchGridViewMedewerker(ref List<Medewerker> medewerkers, String term) {
    medewerkers = medewerkers.Where(m => m.gebruikersnaam.ToLower().Contains(term.ToLower()) ||
                    m.naam.ToLower().Contains(term.ToLower()) ||
                    m.email.ToLower().Contains(term.ToLower()) ||
                    m.rol.ToLower().Contains(term.ToLower())).ToList();
}

public static void SearchGridViewCategorie(ref List<Categorie> categorieen, String term) {
    categorieen = categorieen.Where(c => c.omschrijving.ToLower().Contains(term.ToLower())).ToList();
}

I am trying to make this search method generic, so that I can pass Lists of different types to the same method. I have tried the following:

public static List<object> SearchGridView(List<object> list, String term) {
    IList<PropertyInfo> properties = list.GetType().GetProperties().ToList();
    List<object> tempList = new List<object>();

        foreach(object o in list){
            foreach (var property in properties) {
                if (property.ToString().Contains(term.ToLower())) {
                    tempList.Add(o);
                }
            }
        }
    return tempList;
}

However with this solution I have to convert the List of Type T to a List of objects prior to passing the List in the method.

That is not what I want. I want to pass a List of any type, process it and return a List of the type that has been given as a parameter. Is this possible?

I think that this is what you mean:

public static IList<T> SearchGridView<T>(IList<T> list, String term) 
{
    IList<PropertyInfo> properties = typeof(T).GetProperties();
    var t = term.ToLower();
    return list
        .Where(item =>
            properties
                .Select(p => p.GetValue(item).ToString())
                .Any(v => v.Contains(t)))
        .ToList();
}