Using Linq To Tell if the Elements of an IEnumerable Are Distinct
The Problem
I’ve got an IEnumerable<T> that contains a list of values: I want to know if all of the values in that field are distinct. The function should be easy to use a LINQ extension method and, for bonus points, simply expressed in LINQ itself
One Solution
First, define an extension method
01 public static class IEnumerableExtensions { 02 public static bool AllDistinct<T>(this IEnumerable<T> input) { 03 var count = input.Count(); 04 return count == input.Distinct().Count(); 05 } 06 }
When you want to test an IEnumerable<T>, just write
07 var isAPotentialPrimaryKey=CandidateColumn.AllDistinct();
Analysis
This solution is simple and probably scales as well as any solution in the worst case. However, it enumerates the IEnumerable<T> twice and does a full scan of the IEnumerable even if non-distinct elements are discovered early in the enumeration. I could certainly make an implementation that aborts early using a Dictionary<T,bool> to store elements we’ve seen and a foreach loop, but I wonder if anyone out there can think of a better pure-Linq solution.