添加&的最佳方式使用字典检索列表项

时间:2015-04-17 00:20:15

标签: vb.net list dictionary

我需要为每个用户添加一个项目列表。用户ID是唯一的,每个用户都有多个具有设备名称,设备类型和描述的设备。

所以我创建了一个字典,为每个用户的用户ID添加这些设备的列表作为密钥。

    Dim dicUserDevices As New Dictionary(Of String, List(Of Object()))
    If dicUserDevices.ContainsKey(userid) Then
        dicUserDevices(userid).Add(New Object() {devicename, devicetype, devicedescription})
    Else
           dicUserDevices.Add(userid, New List(Of Object()))
           dicUserDevices(userid).Add(New Object() {devicename, devicetype, devicedescription})
    End If

要检索它,我会执行以下操作:

 Dim devices = dicUserDevices.Item(userid)
 For Each item In devices
            Dim device = {item(0), item(1), item(2)}
 Next

这样可行,但我对使用索引的方式感到不舒服。我做错了吗?这是一种不好的做法吗?它会在某些情况下给我错误吗?什么是最好的方式?

1 个答案:

答案 0 :(得分:1)

我会在那里通过它 - 一个类会有OOP感觉,并且查询简单直观。

Public Class DeviceInfo 
 Public Property User As String
 Public Property DeviceName As String
 Public Property DeviceType As String
 Public Property DeviceDescription As String
End Class

如果您喜欢ContainsKey功能,请使用此功能:

Public Class DeviceInfos : Inherits List(Of DeviceInfo)
  Public Function ContainsKey(user As String) As Boolean
    Return Me.Any(Function(di) di.User = user)
  End Function
End Class

用法:

Private UserDevices As New DeviceInfos

填写您的对象:

If Not UserDevices.ContainsKey(userId) Then
  Dim di As New DeviceInfo 
  di.User = userId
  di.DeviceName = devicename
  di.DeviceType = devicetype
  di.DeviceDescription = devicedescription
  UserDevices.Add(di)
End If

查询:

Dim deviceTypeQuery = From di In UserDevices Where 
                      di.DeviceType = "some type" And
                      di.User = "some user id"