-1

I face with problem in c#. I declare list l is Interface and 3 Object extend(dog,cat,bird) I need to count how many dog in list?. how can I do..please help me to solve! thank u.

  • look at `reflection` -- http://stackoverflow.com/questions/983030/type-checking-typeof-gettype-or-is – Rob Scott Mar 09 '17 at 04:02
  • int count = 0; for (int i = 0; i < l.count; i++) { if (l.ElementAt(i).GetType() == typeof(Dog)) { dem++; } } I'm done – T.Thien Mar 09 '17 at 04:18
  • 1
    Possible duplicate of [Type Checking: typeof, GetType, or is?](http://stackoverflow.com/questions/983030/type-checking-typeof-gettype-or-is) – sazzad Mar 09 '17 at 04:36

1 Answers1

0

Edited to illuminate inheritance concern raised by @Slava, where my initial inclination is that a dog is a dog is a dog:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        IList<object> foo = new List<object> {
            new Bird(),
            new Cat(),
            new Cat(),
            new Dog(),
            new Bird(),
            new Poodle(),
            new Cat(),
            new Dog(),
            new Husky(),
            new Dachshund(),
            new Poodle(),
            new Cat(),
            new Dog()
        };
        var dogCount = foo.Count(x => x is Dog);
        Console.WriteLine($"{dogCount} dogs.");
    }
}

public class Dog
{
    public virtual string Sound { get { return "Woof"; } }
}

public class Dachshund : Dog
{
    public override string Sound { get { return "Ruff"; } }
}

public class Husky : Dog
{
    public override string Sound { get { return "Yarp"; } }
}

public class Poodle : Dog
{
    public override string Sound { get { return "Yip"; } }
}

public class Cat
{
    public string Sound { get { return "Meow"; } }
}

public class Bird
{
    public string Sound { get { return "Tweet"; } }
}

Working Fiddle here.

Substitute whatever test suits best in the predicate, e.g. instead of x is Dog do x.GetType() == typeof(Dog) if only the specific super-type should be counted.

Mark Larter
  • 2,343
  • 1
  • 27
  • 34
  • It will not work, if one of classes is inherited from another. – Slava Utesinov Mar 09 '17 at 05:27
  • @Slava Did OP make that stipulation, that any of the instance in the list could be derived from each other? I saw extends object, i.e. I don't think the question actually pertains to is vs typeof vs GetType, but if it does, someone else will see that and give a different answer. – Mark Larter Mar 09 '17 at 05:37
  • @Slava Moreover, what if the classes are Dachshund, Husky, Poodle, Dog, Bird, and Cat, where the first three derive from Dog? Are you suggesting that we not count Dachshunds, Huskies, Poodles, and Dogs as Dogs? – Mark Larter Mar 09 '17 at 05:50
  • You should ask T.Thien not me. – Slava Utesinov Mar 09 '17 at 05:53
  • @SlavaUtesinov T.Thien didn't say it wouldn't work, you did. – Mark Larter Mar 09 '17 at 05:54