Skip to content

Instantly share code, notes, and snippets.

@gmcelhanon
Last active August 4, 2016 05:00
Show Gist options
  • Save gmcelhanon/ba91ec91628214d375c2ac1f6d6146fa to your computer and use it in GitHub Desktop.
Save gmcelhanon/ba91ec91628214d375c2ac1f6d6146fa to your computer and use it in GitHub Desktop.
ToDictionary method that wraps Linq's ToDictionary, but then lists the keys and identifies duplicates for troubleshooting purposes
/// <summary>
/// Provides a wrapper method around <see cref="Enumerable.ToDictionary"/> to provide details about
/// the duplicate keys encountered (for troubleshooting purposes).
/// </summary>
public static class EnumerableHelper
{
/// <summary>
/// Wraps the standard LINQ ToDictionary extension method to provide additional details about
/// the keys that were to be added to the dictionary.
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TElement"></typeparam>
/// <param name="source"></param>
/// <param name="keySelector"></param>
/// <param name="elementSelector"></param>
/// <param name="equalityComparer"></param>
/// <returns></returns>
public static Dictionary<TKey, TElement> ToDictionaryEx<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
IEqualityComparer<TKey> equalityComparer)
{
try
{
return Enumerable.ToDictionary(source, keySelector, elementSelector, equalityComparer);
}
catch (Exception ex)
{
var keys =
(from s in source
select keySelector(s))
.OrderBy(x => x);
var duplicatedKeys =
(from k in keys
group k by k
into g
where g.Count() > 1
select g.Key);
throw new Exception(string.Format(
@"Duplicate key(s) encountered in ToDictionary invocation:
{0}
All keys:
{1}",
string.Join("\r\n ", duplicatedKeys),
string.Join("\r\n ", keys)), ex);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment