Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting Object of type without counting children objects, possible?

Tags:

c#

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;
}
like image 744
Naglfar705 Avatar asked May 01 '16 13:05

Naglfar705


People also ask

When should a child be able to count objects?

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 it called when children count objects?

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.


2 Answers

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();
like image 122
Ivan Stoev Avatar answered Oct 12 '22 22:10

Ivan Stoev


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)
like image 37
derpirscher Avatar answered Oct 12 '22 22:10

derpirscher