Home > Blockchain >  Convert a List to a Dictionary with a unique numbered key
Convert a List to a Dictionary with a unique numbered key

Time:10-28

How can this code be accomplished using ToDictionary() instead of a For Each

        Dim stringDict As Dictionary(Of String, String) = new Dictionary(Of Integer, String)
        Dim stringList As List(Of String) = {"alpha", "beta", "gamma", "delta"}

        For Each stringItem As String In stringList
            stringDict.Add($"Entry{stringDict.Count 1}",stringItem)
        Next

This is what I am trying to do:

Dim stringDict As Dictionary(Of String, String) = stringList.ToDictionary(Function(a) $"Entry{?}", Function(b) b)

I was hoping there might be a variable with the current row or index, or an incrementor

CodePudding user response:

You can use the overload of Select that gives you the index:

Dim stringDict As Dictionary(Of String, String) = stringList.
    Select(Function(s, index) (Key:=$"Entry{index   1}", Value:=s)).
    ToDictionary(Function(kv) kv.Key, Function(kv) kv.Value)

However, i find your loop more readable. You should also set Option Strict to On, following should give you a compiler error:

Dim stringDict As Dictionary(Of String, String) = new Dictionary(Of Integer, String)

CodePudding user response:

You can use Enumerable.Range (documentation) to create a range of numbers from 1 to the Count of your List and then Enumerable.ToDictionary (documentation) to convert that range to a Dictionary.

Example:

Dim stringList As New List(Of String) From {"alpha", "beta", "gamma", "delta"}
Dim stringDict = Enumerable.Range(1, stringList.Count).ToDictionary(Function(i) $"Entry{i}", Function(i) stringList.Item(i - 1))

Fiddle: https://dotnetfiddle.net/4xHp9g

  • Related