Monday, April 16, 2012

DistinctBy in Linq

Hi Today i just created extension methods for TimeSpan object and Linq object.

we can add Extension methods  to existing methods of c#.

all extension methods are  made from Static  classes.
all extension methods use 'this' keyword.
there is nothing to pass to these methods.
these methods are invoked by the types for which we have generated.



namespace MyExtensions
{
  //Extension methods for TimeSpan object to get number of months and years
    public static class TimeSpanExtensions
    {
        public static int GetYears(this TimeSpan timespan)
        {
            return (int)((double)timespan.Days / 365.2425);
        }
        public static int GetMonths(this TimeSpan timespan)
        {
            return (int)((double)timespan.Days / 30.436875);
        }
    }

//Extension methods for Linq to make DistinctBy()
    public static class LinqExtensions
    {
        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
                            this IEnumerable<TSource> source, Func<TSource, TKey> selector)
        {
            var set = new HashSet<TKey>();
            return source.Where(element => set.Add(selector(element)));
        }
    }
}


you can create a class library with this class and use wherever you want.



No comments:

Post a Comment