tags:

views:

138

answers:

3

I have a list of objects, can be of any type T.

How to select a list of objects that appear in that list only once using linq? For example, if my list is {2,3,4,5,8,2,3,5,4,2,3,4,6}, then the output should be {6,8}.

+1  A: 

Use the Count() function.

    int[] a = {2,3,4,5,8,2,3,5,4,2,3,4,6};

    var selection = from i in a
        where (a.Count(n => n == i) == 1)
        select i;
Cheeso
+6  A: 

You could try this:

int[] arr = { 2, 3, 4, 5, 8, 2, 3, 5, 4, 2, 3, 4, 6 };
var q =
    from g in arr.GroupBy(x => x)
    where g.Count() == 1
    select g.First();
Cornelius
You need to have a method for testing equality for generic `T` however. Very good answer though.
NickLarsen
On a side note, I have found `.GroupBy(...)` to work much better/faster using the functional syntax in experiments. I am not sure what difference is happening, and it might have been specific to my situation however. If I can find it today, I'll post a question later.
NickLarsen
A: 

It's not necessary to count them, you only have to make sure they are unique.

int[] arr = { 2, 3, 4, 5, 8, 2, 3, 5, 4, 2, 3, 4, 6 };
var unique = arr.Where((n, index) => !arr.Take(index).Contains(n) && !arr.Skip(index+1).Contains(n));
Jonas Elfström