背景介绍
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类型取出。
运行结果如下所示: