I am trying to count how many of each type of object are in a dictionary to display them, however when counting objects of Amateur type it also counts all the objects of Professional and Celebrity type because they're children of Amateur. Is there anyway to fix this WITHOUT removing the inheritance and just counting objects of only type Amateur?
Sample code:
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;
}
Between 3 and 4 years of age, they'll also be more adept at counting small sets of objects — "two oranges, four straws" and so on. Most children aren't able to identify numerals or write them, though, until they're 4 or 5.
What is Rational Counting? Rational counting means a child is able to assign the correct number name to each object as they are counted. There is also an understanding of how many objects there are in total.
Of course it's possible. For instance using a simple Where
(or Count
with predicate) with exact type match:
amateurEntries = manager.competitors.Values
.Where(x => x.GetType() == typeof(Amateur)).Count().ToString();
OfType<T>
counts all elements which can be cast to T
which is obviously the case for a subclass of T
. Assumed, that all of your manager.competitors
are either professionals, celebs or amateurs and those sets are distinct, you could count the amateurs indirectly by
int prof = manager.competitors.Values.OfType<Professional>().Count();
int celeb = manager.competitors.Values.OfType<Celebrity>().Count();
int amateurs = manager.competitors.Count() - (prof + celebs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With