Is it possible to count an object of type without taking into account child objects?

I’m trying to calculate how many of each type of object is in the dictionary to display them, however, when calculating amateur-type objects, it also takes into account all objects like “Professional” and “Celebrity”, because they are amateur children. Is there a way to fix this WITHOUT deleting inheritance and just counting objects only of type Amateur?

Code example:

private void GetTotalEntries() { string amateurEntries; string profEntries; string celebEntries; amateurEntries = manager.competitors.Values.OfType<Amateur>().Count().ToString(); profEntries = manager.competitors.Values.OfType<Professional>().Count().ToString(); celebEntries = manager.competitors.Values.OfType<Celebrity>().Count().ToString(); EntriesTextBox.Text = "Amateur Entries:" + amateurEntries + "\nProfessional Entries:" + profEntries + "\nCelebrity Entries:" + celebEntries; } 
+5
source share
2 answers

Of course it is possible. For example, using a simple Where (or Count with predicate) with an exact type match:

 amateurEntries = manager.competitors.Values .Where(x => x.GetType() == typeof(Amateur)).Count().ToString(); 
+6
source

OfType<T> counts all the elements that can be assigned to T , which obviously refers to a subclass of T Suppose all your manager.competitors are professionals, celebrities or amateurs, and these sets are different, you can count fans indirectly

 int prof = manager.competitors.Values.OfType<Professional>().Count(); int celeb = manager.competitors.Values.OfType<Celebrity>().Count(); int amateurs = manager.competitors.Count() - (prof + celebs) 
+2
source

All Articles