Deviruchi D Devourer
Deviruchi D Devourer

Reputation: 341

How can I extract the number of items with the same value in a list?

I have multiple list of int for the ID that are merged together. i need to get the ID that matches the total number of duplicates with a certain number. for example:

int g=3;
List<int> mainlist = new List<int>();
List<int> list1 = new List<int>{1,2,3,4,5,6,7,8,9};
List<int> list2 = new List<int>{2,3,4,5,7,8,9};
List<int> list3 = new List<int>{1,3,5,6,7,9};

mainlist = list1.Concat(list2).Concat(list3).Tolist();

I want to get the ID where the number of duplicate is equal to g

Upvotes: 1

Views: 58

Answers (2)

dkozl
dkozl

Reputation: 33384

You can group your mainlist and select only these groups where Count() == g:

var IDs = mainlist.GroupBy(n => n).Where(n => n.Count() == g).Select(n => n.Key);

Upvotes: 3

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

GroupBy is the best choice in this case,anyway this is an alternative:

 mainlist.Where(x => mainlist.Count(i => x == i) == g).ToList();

Upvotes: 1

Related Questions