如何编写Linq查询获取最低唯一匹配值或按行列排序的最低值
正确实现代码
你可以分两步查询实现需求,逻辑清晰且无副作用:
Structure FoundValue Dim Value As Short Dim Row As Integer Dim Column As Integer End Structure ' 原有初始化代码 Dim UniqueValuesFound As New List(Of Short) From {0, 2, 3} Dim ValuesFoundInPath As New List(Of FoundValue) From { New FoundValue With {.Value = 2, .Row = 1, .Column = 1}, New FoundValue With {.Value = 3, .Row = 0, .Column = 2}, New FoundValue With {.Value = 2, .Row = 0, .Column = 2} ' 新增记录测试可取消下面注释 ', New FoundValue With {.Value = 0, .Row = 2, .Column = 0} } ' 第一步:查询完全匹配UniqueValuesFound的结果,按优先级排序 Dim exactMatch = ValuesFoundInPath. Where(Function(f) UniqueValuesFound.BinarySearch(f.Value) >= 0). OrderBy(Function(f) f.Value). ThenBy(Function(f) f.Row). ThenBy(Function(f) f.Column). FirstOrDefault() ' 第二步:完全匹配无结果时,查询所有记录的最小值 Dim result = If(exactMatch, ValuesFoundInPath. OrderBy(Function(f) f.Value). ThenBy(Function(f) f.Row). ThenBy(Function(f) f.Column). First() )
实现逻辑说明
- 优先筛选
Value存在于UniqueValuesFound中的记录,按Value升序→Row升序→Column升序的优先级排序,取第一条就是最高优先级结果 - 如果没有任何完全匹配的记录,再对所有
ValuesFoundInPath记录执行相同排序规则取第一条,就是部分匹配场景的结果
原有代码问题说明
你之前的写法在Where中捕获了外部变量alreadyFound,依赖遍历顺序的执行逻辑不可靠:Linq to Object默认是延迟执行的,遍历顺序不确定时很容易出现不符合预期的结果,分开两次查询更易维护也没有副作用。
内容的提问来源于stack exchange,提问作者SSpoke
相关产品推荐
相关产品推荐

