我想从键值对列表中获取与给定数据匹配的键值。 我的列表中的数据如下
LeftExistingLayerName
(0)=>{[data1, 0.04#0]}
(1)=>{[data2, 0.04#0]}
(2)=>{[data3, 0.04#0]}
我使用以下代码来获取单个值,例如匹配 data1
Dim LeftExistingLayerName As List(Of KeyValuePair(Of String, String)) = New List(Of KeyValuePair(Of String, String))
Dim result As String()
If LeftExistingLayerName.Where(Function(x) x.Key.Contains(g.LayerName)).Any() Then
Dim result1 = LeftExistingLayerName _
.Where(Function(x) x.Key.Contains(g.LayerName)) _
.Select(Function(x) x.Value) _
.ToString()
result = result1.Split(New String() {"#"}, StringSplitOptions.None)
End If
我想要字符串reslut1中的值并拆分“#”并取出result(0)中的值0.04和result1中的0
我收到此错误
Conversion from string "System.Linq.Enumerable+WhereSele" to type 'Double' is not valid
最佳答案
您没有显示导致问题的代码,因为错误表明“尝试将字符串转换为 double 型”时出现问题。您的代码中没有任何内容说明这一点。
无论如何,重点是......
字符串“System.Linq.Enumerable+WhereSele”显然不是您想要转换为 double 值的字符串。字符串表示形式来自以下事实:您对从 Select
子句返回的 Enumerable
调用 ToString()
,然后尝试将其转换为一个双。
鉴于您已经说过:
I have used following code to get the single value e.g matching data1
我们可以同意,您期望从 Enumerable 查询返回一个单个值,正如 @jmcilhinney 在评论中建议的那样,有多种方法可以为您执行此操作,每种方法都是为您而设计的具体场景。
即
- 第一
- 第一或默认
- 单例
- 单一或默认
我会让您研究区分它们的小细节,但现在出于示例目的,您可以使用 FirstOrDefault
。
所以,你的代码变成:
Dim result As String = LeftExistingLayerName _
.Where(Function(x) x.Key.Contains(g.LayerName)) _
.Select(Function(x) x.Value) _
.FirstOrDefault()
读作“返回 KeyValuePair 的第一个值,其中 KeyValuePair 的键包含 g.LayerName,否则返回引用类型的默认值”
因此,此时,我们可以用分隔符“#”分割字符串,并将数组的第一项、第二项转换为 double 或任何其他类型。
Dim array As String() = LeftExistingLayerName _
.Where(Function(x) x.Key.Contains(g.LayerName)) _
.Select(Function(x) x.Value) _
.FirstOrDefault() _
.Split(New String() {"#"}, StringSplitOptions.None)
' array(0) gets the 0.04 part of your example
' array(1) gets the 0 part of your example
只要始终保证满足谓词 Function(x) x.Key.Contains(s)
就足够了。否则,在对 FirstOrDefault
返回的 null 引用调用 .Split
时,您将收到 NullReferenceException
异常。
如果您想处理这种情况,则可以使用空传播运算符 (?)
。
Dim array As String() = LeftExistingLayerName _
.Where(Function(x) x.Key.Contains(g.LayerName)) _
.Select(Function(x) x.Value) _
.FirstOrDefault() _
?.Split(New String() {"#"}, StringSplitOptions.None)
顺便说一句,你可以简化:
If LeftExistingLayerName.Where(Function(x) x.Key.Contains(g.LayerName)).Any() Then
至:
If LeftExistingLayerName.Any(Function(x) x.Key.Contains(g.LayerName)) Then
关于vb.net - 如何使用linq从vb.net中的键值对列表中的匹配键中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53428267/