DEV Community

Rocky LIU Yan
Rocky LIU Yan

Posted on

How to Use the `ImmutableArray<T>.Builder` Extension Method `ToFrozenDictionary` to Create Efficient Immutable Dictionaries

ImmutableArray<T>.Builder is a class in .NET designed for building immutable arrays (ImmutableArray<T>). It provides an efficient way to construct immutable arrays without repeatedly creating new instances. In .NET 8, you can use the ToFrozenDictionary extension method to build a FrozenDictionary from an ImmutableArray<T>.Builder.

The ToFrozenDictionary extension method can be used to convert elements from an ImmutableArray<T>.Builder instance into an immutable FrozenDictionary<TKey, TValue>. This method is highly efficient for dictionaries that need frequent read access and will not be modified afterward.

Usage

Below is an example of how to use the ToFrozenDictionary extension method to convert an ImmutableArray<T>.Builder into a FrozenDictionary:

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Frozen;

class Program
{
    static void Main()
    {
        // Create an ImmutableArray Builder
        var builder = ImmutableArray.CreateBuilder<KeyValuePair<string, int>>();
        builder.Add(new KeyValuePair<string, int>("apple", 1));
        builder.Add(new KeyValuePair<string, int>("banana", 2));
        builder.Add(new KeyValuePair<string, int>("cherry", 3));

        // Use ToFrozenDictionary method to convert Builder to FrozenDictionary
        FrozenDictionary<string, int> frozenDict = builder.ToFrozenDictionary();

        // Access elements in FrozenDictionary
        Console.WriteLine(frozenDict["apple"]);   // Output: 1
        Console.WriteLine(frozenDict["banana"]);  // Output: 2
        Console.WriteLine(frozenDict["cherry"]);  // Output: 3
    }
}
Enter fullscreen mode Exit fullscreen mode

Example Explanation

  1. Create an ImmutableArray<T>.Builder instance: Create a Builder instance for an ImmutableArray and add key-value pairs to it.
  2. Call the ToFrozenDictionary method: Use the ToFrozenDictionary extension method to convert the builder instance into a FrozenDictionary<TKey, TValue>. This method converts the content of the ImmutableArray into an immutable dictionary.
  3. Access the FrozenDictionary: The FrozenDictionary provides quick read access, making it suitable for scenarios involving frequent lookups.

Using Custom Key Selector and Equality Comparer

You can specify a custom key selector and an equality comparer when using ToFrozenDictionary:

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Frozen;

class Person
{
    public required string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        var builder = ImmutableArray.CreateBuilder<Person>();
        builder.Add(new Person { Name = "Alice", Age = 30 });
        builder.Add(new Person { Name = "Bob", Age = 25 });
        builder.Add(new Person { Name = "Charlie", Age = 35 });

        // Convert Builder to FrozenDictionary using custom key selector and equality comparer
        FrozenDictionary<string, Person> frozenDict = builder.ToFrozenDictionary(
            person => person.Name,  // Key selector
            person => person);      // Value selector

        // Access elements in FrozenDictionary
        Console.WriteLine(frozenDict["Alice"].Age); // Output: 30
        Console.WriteLine(frozenDict["Bob"].Age);   // Output: 25
    }
}
Enter fullscreen mode Exit fullscreen mode

Summary

Using ImmutableArray<T>.Builder and the ToFrozenDictionary method, you can efficiently create an immutable and fast-access dictionary, particularly useful in scenarios involving frequent reads but no further modifications to the data structure.

Top comments (0)