【问题标题】:Check if object exists in a VB.NET dictionary using Primary Key使用主键检查对象是否存在于 VB.NET 字典中
【发布时间】:2015-02-19 16:16:59
【问题描述】:

我有一个这样声明的字典:

Dim customersDictionary As Dictionary(Of Customer, IList(Of String))

客户对象是键,每个客户对象都有一个字符串值列表。

如何返回 bool 检查字典中是否存在 id 为 123 的客户?

【问题讨论】:

  • 我想你可能把字典编错了。如果 ID 是唯一的,使用它作为键,那么customersDictionary.Contains(key) 会告诉你它是否存在。为什么是 IList 值而不是 "123" 甚至 123 (int) 之类的值?
  • 它不是反向构建的,我需要对象本身作为键,然后值是字符串列表。我知道这看起来很奇怪,但字典过去是这样声明的:Dim customersDictionary As Dictionary(Of String, IList(Of String))。现在我需要使用 Customer 对象而不是 String。不过,我将主要在对象中使用 CustomerId。

标签: vb.net linq dictionary


【解决方案1】:

如果您只是想知道您的字典中是否存在具有指定 ID 的客户,那么您可以编写

dim result  = custList.Any(Function(x) x.Key.ID = 123)
if result then
    Console.WriteLine("Customer with ID=123 exists")
End if

如果您想检索给定 ID 的客户,那么

dim result  = custList.Where(Function(x) x.Key.ID = 123).FirstOrDefault()
if result.Key IsNot Nothing Then
    Dim cust = result.Key
    Console.WriteLine("Customer Name is = " & cust.Name) ' or whatever property of your customer
End If

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-08
    • 2012-03-27
    • 2016-03-20
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多