C#学习教程:对不同类型/类的列表使用泛型方法这很简单,但我想要一种可以采用不同类型列表的方法。看下面的例子来澄清一下:SearchGridViewCategorie和SearchGridViewMedewerker方法都是搜索包含搜索词的列表的方法。publicstaticvoidSearchGridViewMedewerker(refListmedewerkers,Stringterm){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();}publicstaticvoidSearchGridViewCategorie(refListcategories,Stringterm){category=category.Where(c=>c.omschrijving.ToLower().Contains(term.ToLower())).ToList();我正在尝试使此搜索方法成为通用的,以便我可以将不同类型的列表传递给同一方法。我尝试了以下方法:publicstaticListSearchGridView(Listlist,Stringterm){IListproperties=list.GetType().GetProperties().ToList();列表tempList=newList();foreach(objectoinlist){foreach(varpropertyinproperties){if(property.ToString().Contains(term.ToLower())){tempList.Add(o);}}}返回临时列表;但是,使用此解决方案,我必须先将T类型的列表转换为对象列表,然后再将列表传递到方法中。那不是我想要的。我想传递任何类型的列表,对其进行处理并返回作为参数给定类型的列表。是否可以?我想这就是你的意思:publicstaticIListSearchGridView(IListlist,Stringterm){IListproperties=typeof(T).GetProperties();vart=term.ToLower();返回列表}看起来您正在尝试简化这种性质的代码:x=>x.property.ToLower().Contains(term.ToLower())其中property是字符串属性,term是您要搜索的文本。如果是这样,您可以使用LINQ扩展方法执行此操作:returnfromelementinsourcefromgetPropertyValueingetPropertyValuesletpropertyValue=getPropertyValue(element)wherepropertyValue.ToLowerInvariant().Contains(searchText)选择元素;然后你会像这样使用它:您可以通过各种不同的方式(正则表达式、表达式列表而不是函数委托等)改进它,但它可能是一个起点。以上就是C#学习教程:使用常用方法,不同类型/类的列表,分享全部内容。如果对你有用,需要了解更多C#学习教程,希望大家多多关注——本文来自网络合集,不代表立场,如涉及侵权,请右击联系管理员删除。如需转载请注明出处:
