C#中IEnumerable.OfType()方法的简单使用

背景介绍

OfType的定义十分简单:IEnumerable.OfType(TResult),如其定义,其中TRsult为所要过滤的类型。由于非泛型集合一律以Object类型存储对象,因此一个非泛型集合可能存储了各种类型,而OfType()方法可以轻松的对指定的类型进行过滤筛选。

代码如下:

        static void Main(string[] args)
        {            
            List<Phone> PhoneLists = new List<Phone>()
            {
                new Phone { Country = "中国", City = "北京", Name = "小米" },
                new Phone { Country = "中国",City = "北京",Name = "华为"},
                new Phone { Country = "中国",City = "北京",Name = "联想"},
                new Phone { Country = "中国",City = "台北",Name = "魅族"},
                new Phone { Country = "日本",City = "东京",Name = "索尼"},
                new Phone { Country = "日本",City = "大阪",Name = "夏普"},
                new Phone { Country = "日本",City = "东京",Name = "松下"},
                new Phone { Country = "美国",City = "加州",Name = "苹果"},
                new Phone { Country = "美国",City = "华盛顿",Name = "三星"},
                new Phone { Country = "美国",City = "华盛顿",Name = "HTC"}

            };
            var Lists = PhoneLists.Select(p => new GetMyPhone().MyPhone(p));
            var myLists = Lists.OfType<MyPhone>();
            foreach (var list in myLists)
            {
                Console.WriteLine($"{list.MyCity} - {list.MyName}");
            }
            Console.Read();
        }
        
        public class Phone
        {
            public string Country { get; set; }
            public string City { get; set; }
            public string Name { get; set; }
        }

        public class MyPhone
        {
            public string MyCity { get; set; }
            public string MyName { get; set; }
        }
        
        public class GetMyPhone
        {
            public object MyPhone(Phone phone)
            {
                if (phone.Country.Equals("中国"))
                {
                    MyPhone myphone = new Program.MyPhone()
                    {
                        MyCity = phone.City,
                        MyName = phone.Name
                    };
                    return myphone;
                }
                else
                {
                    return phone;
                }
            }
        }

 GetMyPhone类中的MyPhone方法取出指定条件的Phone,上述代码中是Country为中国,组成MyPhone类型并返回,如果不满足条件则返回原来的类型,这意味着属性Lists中有两种类型的实体类,而OfType可以将其中为MyPhone类型取出。

运行结果如下所示:

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值