Filter duplicated items from enumerable

c#

Solution

LINQ makes this pretty easy with `GroupBy`:

IEnumerable<String> foo = new[]{ "A", "C", "B", "A", "C", "D", "A" };
Ienumerable<String> result = foo.GroupBy (x => x)          // A=>3,C=>2,B=>1,D=>1
                               .Where(x => x.Count() == 1) // B=>1,D=>1
                               .Select (x => x.Key);       // B,D

- Group them by value

- Filter out those with only 1 entry

- Select the original value

Not sure what you need for performance, but I tend to find GroupBys readable myself.

Problem

I have an unordered enumeration that may contain duplicates, and I want to remove ALL items that have duplicates, and keep only those that occur only once in the original enumeration. Example: A and C are removed since they occur more than once: input {A,C,B,A,C,D,A} output {B,D} A quick and dirty implementation could be: ``` IEnumerable<T> Filter(IEnumerable<T> items) { items.Where(item => items.Count(x => x.Equals(item)) == 1); } ``` Obviously not quick or elegant. The example below is still quadratic (slightly faster), but requires a ToList() call on the input. ``` IEnumerable<T> Filter(IEnumerable<T> items) { List<T> src = items.ToList(); for(int i=0; i<src.Count; i++) { if (src.IndexOf(src[i], i+1) < 0) yield return src[i]; } } ``` How would you do this if you wanted it to be reasonably compact and readable (code wise) while still not brain-dead slow like these implementations?

Original source