ExtensionMethod.NET Home of 876 C#, Visual Basic, F# and Javascript extension methods

AddToList

Given a dictionary where the value type is a List, add items to values of the dictionary, and/or create a list of items as needed, without having to test if the key item already exists.

Source

public static void AddToList<T, K>(this IDictionary<T, HashSet<K>> store, T key, K item)
{

    if (!store.TryGetValue(key, out var value))
    {
        value = new HashSet<K>();
        store[key] = value;
    }
    value.Add(item);
} 
public static void AddToList<T, K>(this IDictionary<T, List<K>> store, T key, K item)
{

    if (!store.TryGetValue(key, out var value))
    {
        value = new List<K>();
        store[key] = value;
    }
    value.Add(item);
}

Example

Dictionary<int, List<string>> carNamesByManufacturerId = new Dictionary<int, List<string>>();

var honda = 1;
var ford = 2;


carNamesByManufacturerId.AddToList(honda, "Accord");
carNamesByManufacturerId.AddtoList(honda, "CRX");

carNamesByManufacturerId.AddToList(ford, "Focus");
carNamesByManufacturerId.AddToList(ford, "Edge");

//without extension method (old way)
if (!carNamesByManufacturerId.TryGetValue(ford, out fords))
{
   fords = new List<string>();
   carNamesByManufacturerId[ford] = fords;
}
fords.Add("Edge");

Author: Eric Robishaw

Submitted on: 23 okt 2020

Language: csharp

Type: System.Collections.Generic.IDictionary

Views: 2988