.netdictionary

Make a comma-separated string of the keys in a .Net dictionary (no Linq!)


Our 15+ YO VB.net app has a number of Dictionary(Of Integer, <some object type>). Examples include Dictionary(Of Integer, Accounts) and Dictionary(Of Integer, Users).

I would like to write a generic helper method to return the keys as a comma-separated string. This seems more difficult than I imagined.

The app is cross-platform and Linq is not available. If it was I would simply pass the result Integer() from ToArray and be done.

My initial thought was to use a method that took Dictionary(Of Integer, Object), but a Dictionary(Of Integer, Accounts) is not a Dictionary(Of Integer, Object). I suspect this is the solution, but I simply don't have the correct syntax for the second type?

I also thought that passing the KeyCollection (from .Keys) would work, but that returns a Dictionary of the same type (which I admit to finding surprising) so that doesn't appear to help.

Is there a simple solution here?


Solution

  • You should be able to use generics to create an extension method without worrying about the type of the dictionary's values, so long as the key is an integer.

    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
    

    Hopefully this will give you what you want though.


    CAVEAT

    As I'm not a VB.NET developer the code above was converted from the equivalent C#, below, using https://www.codeconvert.ai/csharp-to-vb.net-converter.

    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);
        }
    }