基于VB.NET Framework 4.8如何实现类所有属性的通用匹配搜索?
问题:VB.NET Framework 4.8实现通用属性匹配搜索
使用VB.NET Framework 4.8,能否实现搜索类的所有属性以匹配指定值,只要对象的任一属性匹配就将其返回?
现有如下People类及单个属性匹配的示例代码:
Public Class People Public Property kids As List(Of String) Public Property first As String Public Property last As String Public Property age as Integer End Class Dim test As List(Of People) = PeopleList.Where( Function(p) Return p.first = sometextbox.text End Function ).ToList()
已知可通过上述方式单独匹配单个属性,但希望实现搜索所有属性的通用匹配:比如first不匹配但last匹配,或kids列表中存在匹配文本框内容的项。若采用Or串联每个属性的方式,因类属性较多且需具备可扩展性(新增属性时无需修改匹配逻辑),故希望寻求更优方案。
曾尝试通过反射获取PropertyInfo,但未找到可行方向,代码如下:
'I have tried something like the below but feel like it is heading towards a dead end Dim properties As PropertyInfo() = GetType(People).GetProperties() for each prop in Properties prop.getvalue()
核心需求为:过滤对象列表,返回所有任一属性匹配搜索条件的对象。
解决方案
你可以借助反射实现通用的属性匹配逻辑,遍历对象的所有公共属性,针对不同类型的属性做针对性匹配,这样新增属性时无需修改过滤逻辑。以下是完整实现:
通用匹配方法
Imports System.Reflection Imports System.Collections.Generic Private Function DoesAnyPropertyMatch(targetObject As Object, searchValue As String) As Boolean If targetObject Is Nothing OrElse String.IsNullOrEmpty(searchValue) Then Return False End If ' 统一转为小写,实现不区分大小写的匹配(可根据需求调整) Dim searchLower = searchValue.ToLowerInvariant() ' 获取对象的所有公共实例属性 Dim properties = targetObject.GetType().GetProperties(BindingFlags.Public Or BindingFlags.Instance) For Each prop In properties Dim propValue = prop.GetValue(targetObject) If propValue Is Nothing Then Continue For End If ' 处理字符串类型属性 If TypeOf propValue Is String Then Dim strValue = DirectCast(propValue, String).ToLowerInvariant() If strValue.Contains(searchLower) Then Return True End If ' 处理值类型(如Integer、DateTime等) ElseIf propValue.GetType().IsValueType Then Dim strValue = propValue.ToString().ToLowerInvariant() If strValue.Contains(searchLower) Then Return True End If ' 处理字符串集合(如List(Of String)) ElseIf TypeOf propValue Is IEnumerable(Of String) Then Dim stringList = DirectCast(propValue, IEnumerable(Of String)) If stringList.Any(Function(item) Not String.IsNullOrEmpty(item) AndAlso item.ToLowerInvariant().Contains(searchLower)) Then Return True End If ' 可扩展支持其他类型:比如自定义类、数值集合等 ' ElseIf TypeOf propValue Is IEnumerable(Of Integer) Then ' 对应处理逻辑 ' End If Next Return False End Function
调用示例
直接在Where条件中调用上述方法即可:
Dim searchText = sometextbox.Text.Trim() Dim matchedPeople = PeopleList.Where(Function(p) DoesAnyPropertyMatch(p, searchText)).ToList()
扩展性说明
如果后续新增属性或者需要支持其他数据类型(比如自定义类、List(Of Integer)等),只需要在DoesAnyPropertyMatch方法中添加对应的类型判断和处理逻辑即可,无需修改过滤集合的调用代码。
内容的提问来源于stack exchange,提问作者Quinn Nash
相关产品推荐
相关产品推荐

