这里我建立了三个测试类 catfamily ,cat与tiger

cat 与tiger继承自catfamily,catfamily是抽象类,有一个方法Miao()。建立一个catfamily的List泛型 ,然后通过LINQ去查询cat 或是tiger

 

namespace LinqTest
{
    class Cats:CatFamily
    {
        public override void Miao()
        {
            Console.WriteLine("喵~~");            
        }
    }
}
 
namespace LinqTest
{
    class Tigers:CatFamily
    {
        public override void Miao()
        {
            Console.WriteLine("嗷~~~~~~");
        }
    }
}
 
namespace LinqTest
{
    class Cats:CatFamily
    {
        public override void Miao()
        {
            Console.WriteLine("喵~~");            
        }
    }
}
上面是实现的三个测试类,下面是主运行程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //实现CatFamily的LIST泛型
            List<CatFamily> lstCats = new List<CatFamily>();
            Cats _cat = new Cats();
            Tigers _tiger = new Tigers();

            lstCats.Add(_cat);
            lstCats.Add(_tiger);

            Console.WriteLine("LINQ Test");
            //通过LINQ查询出相应的子类
            var getLinqTiger = from lt in lstCats
                            where lt.GetType() == typeof(Tigers)
                            select lt;


            var getLinqCat = from lc in lstCats
                         where lc.GetType() == typeof(Cats)
                         select lc;

            ((Tigers)getLinqTiger.First()).Miao();
            ((Cats)getLinqCat.First()).Miao();       
        }
    }    
}

我这里将两个方法都查出来了,如果是想都实现的话完全可以通过FOREACH去实现.因为是做测试所以我没有加入相关的判断代码。在使用FIRST()方法前应该加入对getLinqTiger中Count 的判断。

posted on 2007-08-31 22:55  forrestsun  阅读(409)  评论(0编辑  收藏  举报