OfType 的使用

C# OfType 的使用

 

该关键字主要用在非泛型到泛型之间的转化,在有些场合还是很有用的;比如:在使用非泛型的时候,想使用LINQ表达式进行结果查询

如:声明非泛型集合

System.Collections.ArrayList fruits = new System.Collections.ArrayList(5);
fruits.Add("Mango");
fruits.Add("Orange");
fruits.Add("Apple");

fruits.Add(32);
fruits.Add("Banana");

若我们想得到含有“n”字母的水果,则使用如下方式

现将fruits转化为兼容 IEnumerable<T>的类型

var query = fruits.OfType<string>(); //只取出满足 string 的对象;

在使用LINQ表达式即可完成目的:

var result= from c in query where c.contain("n") select c;

今天突然在书上看到该关键字,感觉很有用就随笔记录下来了,仅供参考;

void Main()
{
    //請注意:ArrayList 並未實做 IEnumerable<T>,所以不能應用 LINQ
    ArrayList ary = new ArrayList();
    //加入三個顧客資料
    ary.Add(new Customer {Id = 1, Name = "Leo", Age = 36});
    ary.Add(new Customer {Id = 2, Name = "Rose", Age = 28});
    ary.Add(new Customer {Id = 3, Name = "Alvin", Age = 2});
    //加入三個顧客的訂單資料
    ary.Add(new Order {CustomerId = 3, OrderDate = new DateTime(2011, 10, 9), Total = 2940});
    ary.Add(new Order {CustomerId = 2, OrderDate = new DateTime(2012, 10, 10), Total = 3849});
    ary.Add(new Order {CustomerId = 1, OrderDate = new DateTime(2011, 12, 1), Total = 500});
    ary.Add(new Order {CustomerId = 1, OrderDate = new DateTime(2012, 2, 28), Total = 1234});
    ary.Add(new Order {CustomerId = 2, OrderDate = new DateTime(2012, 5, 20), Total = 9520});
    //透過 OfType 過濾出訂單資料,並用 Where 條件查出小於千元的訂單
    var queryOrder = from e in ary.OfType<Order>()
                where e.Total < 1000
                select e;
    foreach (var e in queryOrder)
    {
        Console.WriteLine(e.ToString());
    }
}
//顧客基本資料類別
public class Customer
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int Age { get; set; }
    
    public override string ToString()
    {
        return string.Format("Id = {0}, Name = {1}, Age = {2}", 
                                Id, Name, Age);
    }
}
//訂單基本資料類別
public class Order
{
    public int CustomerId { get; set; }
    public DateTime OrderDate { get; set; }
    public double Total { get; set; }
    
    public override string ToString()
    {
        return string.Format("CustomerId = {0}, OrderDate = {1}, Total = {2}", 
                                CustomerId, OrderDate, Total);
    }
}
//輸出:
//CustomerId = 1, OrderDate = 2011/12/1 上午 12:00:00, Total = 500

 

posted on 2019-12-30 18:03  jshchg  阅读(747)  评论(0编辑  收藏  举报

导航