Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: Select Elements that Only Appear Once in a List

Tags:

c#

linq

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}.

like image 914
Graviton Avatar asked Apr 06 '10 11:04

Graviton


2 Answers

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();
like image 117
Cornelius Avatar answered Oct 20 '22 23:10

Cornelius


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;
like image 25
Cheeso Avatar answered Oct 20 '22 22:10

Cheeso