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

Dictionary AddRange

Add an enumeration of items to a dictionary. There are times when you may want to simply add to a dictionary at different points in the pipe, instead of always creating it from a given set of entities This extension allows you to add items to a dictionary from a select statement, or some other enumerable.

Source

public static void AddRange<K, T, TI>(this IDictionary<K, T> target, IEnumerable<TI> source, Func<TI, K> key, Func<TI, T> selector, bool set = true)
{
    source.ForEach(i =>
    {
        var dKey = key(i);
        var dValue = selector(i);
        if (set)
        {
            target[dKey] = dValue;
        }
        else
        {
            target.Add(key(i), selector(i));
        }
    });

}

Example

class Car
{
    int Id {get;set;}
    string Name {get;set;}
}

public void AddCars (IDictionary<int, string> carDictionary, Car[] cars)
{
 
     carDictionary.AddRange(cars, c=> c.Id, c => c.Name);
}
public Enum Makers 
{
   Ford,
   Chevy
}
public Car[] GetCars(Makers maker)
{
    if (manufacturer == Makers.Ford)
    {
        return 
          new Car[] 
      {
        new Car(1, "Ford Focus"),
        new Car(2, "Ford Edge") 
      };
    else {
     //return some other cars
   }
}

Dictionary<int,string> carsById = new Dictionary<int,string>();
var fords = GetCars(Makers.Ford);
//do something with fords
carsById.AddRange(fords);

var chevys = GetCars (Makers.Chevy);
//do something with chevys
carsById.AddRange(chevys);


//The alternative, without the extension method is something like:
fords.Union(chevys).ToDictionary(...);

//but there are times when you may want to simply add to a dictionary at different points in the pipe, instead of always creating it from a given set of entities

Author: Eric Robishaw

Submitted on: 23 okt. 2020

Language: csharp

Type: System.Collections.Generic.IDictionary

Views: 9425