C# 如何通过键获取值以及使用linq获取另一个值?程序设计
我想通过linq查询在字典中的index=“x”和key=“y”获得imglst\u索引C# 如何通过键获取值以及使用linq获取另一个值?程序设计,c#,linq,C#,Linq,我想通过linq查询在字典中的index=“x”和key=“y”获得imglst\u索引 Public ets As New Dictionary(Of String, info) Public Class info Public Property index As Integer Public Property imglst_index As Integer End Class 这是我的代码。这是您的操作方式 For Each subKey As Strin
Public ets As New Dictionary(Of String, info)
Public Class info
Public Property index As Integer
Public Property imglst_index As Integer
End Class
这是我的代码。这是您的操作方式
For Each subKey As String In subKeys
Dim result = exts.FirstOrDefault(Function(x) x.Key = subkey AndAlso x.Value.ext_icon_index = subkey.DefaultIcon.Index).Value.ext_imglst_index
if result>0 then item2.imageindex=result
Dim item As New ListViewItem(subKey)
item.ImageIndex = ImageList.Images.Count - 1
item.Tag = subKey
Items.Add(item)
exts.Add(subkey, New ext_info With {.ext_icon_index = subkey.DefaultIcon.Index, .ext_imglst_index = item.ImageIndex})
Next subKey
试试这个
Dim result = ets.First(Function(x) x.Key = "y" AndAlso x.Value.index="x") _
.Value _
.imglst_index
异常:捕获:“对象引用未设置为对象的实例。”(System.NullReferenceException)获取此错误。返回第一个中添加的两个结果后post@ErolCimen您可能需要将该行代码拆分为多个语句以检查空值。例如,第一条语句将只具有FirstOrDefault。仅当结果不为空时,您将对结果执行空检查,并访问
值
属性。这同样适用于imglst_索引属性。
Module Module1
Sub Main()
Dim infos As New List(Of info)
ets = infos.GroupBy(Function(x) x.index).ToDictionary(Function(x) x.Key, Function(y) y.FirstOrDefault())
End Sub
Public ets As New Dictionary(Of Integer, info)
Public Class info
Public Property index As Integer
Public Property imglst_index As Integer
End Class
End Module