在 .Net 字典中创建一个以逗号分隔的键字符串(没有 Linq!)

问题描述 投票:0回答:1

我们的 15+ YO VB.net 应用程序有许多

Dictionary(Of Integer, <some object type>)
。示例包括
Dictionary(Of Integer, Accounts)
Dictionary(Of Integer, Users)

我想编写一个通用的辅助方法来以逗号分隔的字符串形式返回键。这似乎比我想象的要困难。

该应用程序是跨平台的,Linq 不可用。如果是的话,我只需传递来自

Integer()
的结果
ToArray
即可完成。

我最初的想法是使用采用

Dictionary(Of Integer, Object)
的方法,但是
Dictionary(Of Integer, Accounts)
不是
Dictionary(Of Integer, Object)
。我怀疑这解决方案,但我根本没有第二种类型的正确语法?

我还认为传递

KeyCollection
(来自
.Keys
)会起作用,但是会返回相同类型的字典(我承认这令人惊讶),所以这似乎没有帮助。

这里有简单的解决方案吗?

.net dictionary
1个回答
0
投票

您应该能够使用泛型来实现创建字典的扩展方法,而不必担心字典值的类型。

在 C# 中这很简单(我不是 VB.NET 开发人员,但是嘿,这都是 .NET):

using System;
using System.Collections.Generic;

var dict = new Dictionary<int, object>()
{
    { 1, new { } },
    { 2, new { } },
    { 3, new { } },
    { 4, new { } },
};

Console.WriteLine(dict.CommaSeparatedKeys());

public static class DictionaryExtensions
{
    public static string CommaSeparatedKeys<TValue>(this IDictionary<int, TValue> dict)
    {
        return string.Join(",", dict.Keys);
    }
}

在 VB 中我相信等价的是:

Imports System
Imports System.Collections.Generic

Module Module1
    Sub Main()
        Dim dict As New Dictionary(Of Integer, Object) From {
            {1, New Object()},
            {2, New Object()},
            {3, New Object()},
            {4, New Object()}
        }

        Console.WriteLine(dict.CommaSeparatedKeys())
    End Sub
End Module

Module DictionaryExtensions
    <System.Runtime.CompilerServices.Extension>
    Public Function CommaSeparatedKeys(Of TValue)(dict As IDictionary(Of Integer, TValue)) As String
        Return String.Join(",", dict.Keys)
    End Function
End Module

VB 代码是使用 https://www.codeconvert.ai/csharp-to-vb.net-converter 从 C# 转换而来的。希望这能给你你想要的东西。

© www.soinside.com 2019 - 2024. All rights reserved.