Skip to content

Instantly share code, notes, and snippets.

@caseywatson
Created October 14, 2016 15:56
Show Gist options
  • Save caseywatson/3148cba6970ac673f602853557288e62 to your computer and use it in GitHub Desktop.
Save caseywatson/3148cba6970ac673f602853557288e62 to your computer and use it in GitHub Desktop.
ElementAtOrDefault for Dictionaries
using System;
using System.Collections.Generic;
namespace Foo
{
public static class DictionaryExtensions
{
public static TValue ElementAtOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
if (dictionary == null)
throw new ArgumentNullException(nameof(dictionary));
return (dictionary.ContainsKey(key) ? dictionary[key] : default(TValue));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment