LINQ学習ノート(03)


Filtering---OfType
LINQには、選択する結果をフィルタリングする方法が複数あるが、OfTypeはその1つである.
くだらないことは言わないで、code.
class Program
    {
        abstract public class Person
        {
            public string mName;

            public Person(string strName)
            { 
                mName = strName;
            }

            public virtual void SayHello()
            {
            }
        }

        public class Teacher : Person
        {
            public Teacher(string strName)
                : base(strName)
            {
            }
            public override void SayHello()
            {
                Console.WriteLine("Hi, this is {0} and I am a teacher!", mName);
            }
        }

        public class Student : Person
        {
            public Student(string strName)
                :base(strName)
            {
            }

            public override void SayHello()
            {
                Console.WriteLine("Hi, this is {0} and I am a Student!", mName);
            }
        }

        static void Main(string[] args)
        {
            Person Zhao = new Teacher("Zhao");
            Person Qian = new Teacher("Qian");
            Person Sun = new Teacher("Sun");
            Person Li = new Teacher("Li");

            Person Zhou = new Student("Zhou");
            Person Wu = new Student("Wu");
            Person Zheng = new Student("Zheng");
            Person Wang = new Student("Wang");

            List<Person> persons= new List<Person>();

            persons.Add(Zhao);
            persons.Add(Qian);
            persons.Add(Sun);
            persons.Add(Li);

            persons.Add(Zhou);
            persons.Add(Wu);
            persons.Add(Zheng);
            persons.Add(Wang);
            var vars = persons.OfType<Student>();
            foreach (Student p in vars)
            {
                p.SayHello();
            }
        }
    }