VB.NET自定义类列表元素匹配的函数实现需求
VB.NET:匹配自定义类列表生成组件-材料对应数组
1. 自定义类定义
先明确两个自定义类的标准实现(包含属性与构造函数):
Public Class materialsDefinition Public Property id As Integer Public Property name As String Public Sub New(id As Integer, name As String) Me.id = id Me.name = name End Sub End Class Public Class componentInfo Public Property componentName As String Public Property materialID As Integer Public Sub New(componentName As String, materialID As Integer) Me.componentName = componentName Me.materialID = materialID End Sub End Class
2. 示例数据准备
' 材料列表(用作匹配字典) Dim materials As New List(Of materialsDefinition) From { New materialsDefinition(1, "A_286"), New materialsDefinition(2, "17-4PH") } ' 组件信息列表 Dim components As New List(Of componentInfo) From { New componentInfo("Pin", 1), New componentInfo("Nut", 2) }
3. 实现方案
方案1:使用List.Find方法
适合数据量不大的场景,代码简洁易读,通过Lambda表达式指定匹配条件:
Public Function GetComponentMaterialPairs(components As List(Of componentInfo), materials As List(Of materialsDefinition)) As List(Of Tuple(Of String, String)) Dim result As New List(Of Tuple(Of String, String)) For Each comp In components ' 根据组件的materialID查找对应材料 Dim matchedMaterial = materials.Find(Function(mat) mat.id = comp.materialID) ' 仅添加匹配成功的条目(可按需调整为保留未匹配组件) If matchedMaterial IsNot Nothing Then result.Add(Tuple.Create(comp.componentName, matchedMaterial.name)) End If Next Return result End Function
方案2:转Dictionary优化查找效率
如果材料列表数据量大,将其转为Dictionary可将单次查找复杂度从O(n)降至O(1),大幅提升性能:
Public Function GetComponentMaterialPairs(components As List(Of componentInfo), materials As List(Of materialsDefinition)) As List(Of Tuple(Of String, String)) ' 预处理材料列表为字典,后续查找直接复用 Dim materialDict = materials.ToDictionary(Function(mat) mat.id, Function(mat) mat.name) Dim result As New List(Of Tuple(Of String, String)) For Each comp In components Dim materialName As String ' 尝试获取匹配的材料名,成功则添加条目 If materialDict.TryGetValue(comp.materialID, materialName) Then result.Add(Tuple.Create(comp.componentName, materialName)) End If Next Return result End Function
方案3:使用LINQ Join(最简洁)
LINQ的Join操作内部会自动优化匹配逻辑,代码最简洁,可读性极强:
' 直接生成结果列表 Dim componentMaterialPairs = From comp In components Join mat In materials On comp.materialID Equals mat.id Select Tuple.Create(comp.componentName, mat.name) ToList()
4. 处理列表长度不一致的情况
- 若材料列表比组件列表长:未被组件引用的材料不会出现在结果中,无需额外处理;
- 若组件的
materialID无匹配材料:- 默认方案会忽略该组件;
- 若需保留组件名并将材料名设为空,可调整代码:
- 基于
Find的方式:result.Add(Tuple.Create(comp.componentName, If(matchedMaterial IsNot Nothing, matchedMaterial.name, String.Empty))) - 基于LINQ
GroupJoin的方式:Dim componentMaterialPairs = From comp In components Group Join mat In materials On comp.materialID Equals mat.id Into MatchedMaterials = Group Select Tuple.Create(comp.componentName, If(MatchedMaterials.Any(), MatchedMaterials.First().name, String.Empty)) ToList()
- 基于
内容的提问来源于stack exchange,提问作者Violeta Ayon
相关产品推荐
相关产品推荐

