Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine the number of unique derived types in an array?

Tags:

arrays

c#

.net

linq

I have the following classes

Customer Class

abstract class Customer
{
    public int id;
    public string name;
    public double balance;
}

class NormalCustomer

class NormalCustomer: Customer
{
}

class SubscriberCustomer

class SubscriberCustomer:Customer
{
    public int LandMinutes;
    public int MobileMinutes;
}

If we create an array of Customers

Customer[] customers = new Customer[100];
customers[0]=new NormalCustomer();
customers[1] = new NormalCustomer();
customers[2] = new SubscriberCustomer();
customers[3] = new NormalCustomer();
customers[4] = new SubscriberCustomer(); 

The question is how do I know how many object in the array are NormalCustomers and how many object in the array are SubscriberCustomers?

like image 479
Nidal Avatar asked Dec 18 '22 15:12

Nidal


1 Answers

You can use OfType extension method

customers.OfType<NormalCustomer>().Count() 

You will need to import System.Linq namespace with a using directive:

using System.Linq;
like image 140
Aleksey L. Avatar answered Jan 28 '23 18:01

Aleksey L.