14 Apr 2011 @ 9:59 PM 

Here is a quick extension method to sort a collection by a given property specified though generics. The extension method then uses a hashset to determine duplicates. This is excellent when paired with unique ids.

        public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
        {
            HashSet<TKey> knownKeys = new HashSet<TKey>();
            foreach (T element in source)
            {
                if (knownKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }
Posted By: Boyd
Last Edit: 14 Apr 2011 @ 10:31 PM

EmailPermalink
Tags
Tags: , , ,
Categories: .Net, Programming


 

Responses to this post » (None)

 
Tags
Comment Meta:
RSS Feed for comments

 Last 50 Posts
Change Theme...
  • Users » 3
  • Posts/Pages » 30
  • Comments » 0
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

GeekPub



    No Child Pages.