While operating with collections, sometime we would like to perform Distinct on column, to achieve this we need to write the extension method.
public static class StaticDistinct { public static IEnumerable<TSource> DistinctBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TKey> knownKeys = new HashSet<TKey>(); foreach (TSource element in source) { if (knownKeys.Add(keySelector(element))) { yield return element; } } } } // USAGE var distinctUsers = users.DistinctBy(x => x.EmailId).ToList();
This example also demostrate what are extension methods and syntax of extension method.
Extension Methods:
#1) These are static methods, so these method should be surronded by static class
#2) These method signature would start this keyword. Let’s say you want to write extension method to string then the method would be some thing like below.
// DEFINE EXTENSION METHOD public static string ImExtensionMethod(this string value) { return "Hurray! I am EXTENSION method"; } //USAGE string whoAreYou = "Hello"; whoAreYou.ImExtensionMethod();
By now you should be knowing why did we define DISTINCTBY as extension method
Happy Kooding…. Hope this helps!