Gabriel Lemire
Gabriel Lemire

Reputation: 27

Find duplicates that appear exactly twice in a list

I have a list that is automatically generated

var v = new List<int>(1000);
var generateur = new Random(1);
for (int i = 0; i != 1000; ++i)
     v.Add(generateur.Next(10000));

And I want to find how many number repeat exactly twice using only one lambda expression.

Upvotes: 1

Views: 448

Answers (2)

MethodMan
MethodMan

Reputation: 18843

List<String> listDup = new List<String> { "6", "1", "2", "4", "6", "5", "1" };
var duplicates = listDup.GroupBy(n => n)
                 .Where(grp => grp.Count() == 2)
                 .Select(grp => grp.Key).ToList();

Yields a list containing 6 and 1 since these show up exactly twice in the list.

using the above code to get a total count of items that were in the list 2 times

int count2Times = listNonDup.GroupBy(x => x).Where(x => x.Count() == 2).Count();

Upvotes: 3

Steve
Steve

Reputation: 216303

If I understand your question (and the integer that you use as result in your code comment) it seems that you want to Count the number of times a group of two numbers appears. Not a list of these numbers.

Then the solution is

 int repeated = v.GroupBy(x => x).Where(g => g.Count() == 2).Count();

Upvotes: 4

Related Questions