Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count the occurence of each number in list A that is exist in list B and return zero if not existed?

This is my first question in this community and I would like to get an answer to my problem ,
Suppose that I have two lists A and B:

List<int> listA = new List<int>();
List<int> listB = new List<int>();

listA.Add(1);
listA.Add(2);
listA.Add(8);


listB.Add(1);
listB.Add(1);
listB.Add(1);
listB.Add(2);
listB.Add(2);
listB.Add(2);
listB.Add(2);

I would like to count the occurrences of each element in listB that already existed in listA and add zero if does not exist:

This is what I’ve tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var result = listB.GroupBy(x => x).ToDictionary(k => k.Key, v => v.Count());
foreach(var res in result.Values)
    Console.WriteLine(res); // it will print only {3,4} 

The expected result will be :

// { 3,4,0}  => 3 is the occurrences number of 1 , 4 is the occurrences number of 2 ,and 0 is the number occurrences of 8

How can I achieve this result?

>Solution :

I would use the linq .Count() extension, which will count the number of items that satisfy a condition. Yes, this will iterate the list more times than is necessary, but it doesn’t create any unnecessary objects, and it is very readable:

var countOccurences = new List<int>();
        
foreach (var inA in listA)
{
    countOccurences.Add(listB.Count(inB => inB == inA));
}
    
Console.WriteLine(string.Join(", ", countOccurences));

Once you’ve got the loop working, then it should be easy to see that it can be done in a single statement:

var countOccurences = listA.Select(inA => listB.Count(inB => inA == inB));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading