Custom Distinct Comparer in LINQ

List<DateTime> years = newsItems.Where(x => x.Date.HasValue).Select(x => x.Date.Value).Distinct(new YearComparer()).ToList();
class YearComparer : IEqualityComparer<DateTime>
    {
        public bool Equals(DateTime x, DateTime y)
        {
 
            return x.Year.Equals(y.Year);
        }
 
        public int GetHashCode(DateTime obj)
        {
            return obj.Year.GetHashCode();
        }
    }

 
  1. martinrichards posted this
Blog comments powered by Disqus