Enumerable.OfType)>) 方法

來源:互聯網
上載者:User
 

根據指定類型篩選 IEnumerable 的元素。

命名空間:  System.Linq
程式集:  System.Core(在 System.Core.dll 中)

 

此方法通過使用順延強制實現。即時傳回值為一個對象,該Object Storage Service執行操作所需的所有資訊。只有通過直接調用對象的 GetEnumerator 方法或使用 Visual C# 中的 foreach(或 Visual Basic 中的 For Each)來枚舉該對象時,才執行此方法表示的查詢。

OfType<(Of <(TResult>)>)(IEnumerable) 方法僅返回 source 中那些可以轉換為 TResult 類型的元素。如果元素不能轉換為 TResult 類型,但卻不想接收異常,則使用 Cast<(Of <(TResult>)>)(IEnumerable)。

此方法是少數標準查詢運算子方法之一,標準查詢運算子方法可應用於含有非參數化型別(如 ArrayList)的集合。這是因為 OfType<(Of <(TResult>)>) 擴充了類型 IEnumerable。OfType<(Of <(TResult>)>) 不僅無法應用於基於參數化的 IEnumerable<(Of <(T>)>) 類型的集合,也無法應用於基於非參數化的 IEnumerable 類型的集合。

通過將 OfType<(Of <(TResult>)>) 應用於實現 IEnumerable 的集合,可以獲得使用標準查詢運算子查詢集合的能力。例如,將 Object 的型別參數指定為 OfType<(Of <(TResult>)>) 將返回一個對象,其類型為 C# 中的 IEnumerable<Object>IEnumerable(Of Object) 中的 Visual Basic,標準查詢運算子可應用於該對象。

C#代碼:

Code
System.Collections.ArrayList fruits = new System.Collections.ArrayList(4);
fruits.Add("Mango");
fruits.Add("Orange");
fruits.Add("Apple");
fruits.Add(3.0);
fruits.Add("Banana");

// Apply OfType() to the ArrayList.
IEnumerable<string> query1 = fruits.OfType<string>();

Console.WriteLine("Elements of type 'string' are:");
foreach (string fruit in query1)
{
    Console.WriteLine(fruit);
}

// The following query shows that the standard query operators such as 
// Where() can be applied to the ArrayList type after calling OfType().
IEnumerable<string> query2 =
    fruits.OfType<string>().Where(fruit => fruit.ToLower().Contains("n"));

Console.WriteLine("\nThe following strings contain 'n':");
foreach (string fruit in query2)
{
    Console.WriteLine(fruit);
}

// This code produces the following output:
//
// Elements of type 'string' are:
// Mango
// Orange
// Apple
// Banana
//
// The following strings contain 'n':
// Mango
// Orange
// Banana

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.