feanz
11/26/2013 - 11:44 AM

DistinctBy Linq Expression

DistinctBy Linq Expression

/// <summary>
		/// Select distinct elements in collection on a given property
		/// </summary>
		/// <typeparam name="TSource"></typeparam>
		/// <typeparam name="TKey"></typeparam>
		/// <param name="source">The collection to filter</param>
		/// <param name="keySelector">The property to distinct collection by</param>
		/// <returns></returns>
		public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
		{
			var seenKeys = new HashSet<TKey>();
			return source.Where(element => seenKeys.Add(keySelector(element)));
		}