using System;
using System.Collections.Generic;
using System.Linq;
namespace DFEngine
{
///
/// Class that extends the use of the List class.
///
public static class DictionaryExtensions
{
///
/// The object to lock for list access.
///
private static readonly object LockObject = new object();
///
/// Adds an object to the list in a thread-safe, exception-safe
/// manner.
///
/// The source list.
/// The value to add.
public static void AddSafe(this Dictionary source, TKey key, TValue value)
{
if (key == null || value == null)
{
return;
}
lock (LockObject)
{
if (source.ContainsKey(key))
{
source[key] = value;
return;
}
source.Add(key, value);
}
}
///
/// Tries to get the object at the specified key. Returns default if it does not exist,
/// instead of throwing an exception.
///
/// The type of the key.
/// The type of the value.
/// The dictionary being searched.
/// The key of the value.
public static TValue GetSafe(this Dictionary source, TKey key)
{
return source.ContainsKey(key) ? source[key] : default(TValue);
}
///
/// Runs a for loop on dictionary, backwards, in a thread-safe manner.
///
/// The source dictionary.
/// The action to perform on the item.
public static void ForBackwards(this Dictionary source, Action action)
{
lock (LockObject)
{
foreach (var item in source.Reverse())
{
action(item.Key, item.Value);
}
}
}
///
/// Returns a new dictionary filtered using the predicate provided.
///
public static Dictionary Filter(this Dictionary source, Func, int, bool> predicate)
{
lock (LockObject)
{
return new Dictionary(source.Where(predicate));
}
}
}
}