本文章是由人工翻譯。 將指標移到文章內的文字上方即可查看原文。
譯文
原文
本主題尚未接受評分 - 為這個主題評分

Enumerable.FirstOrDefault<TSource> 方法 (IEnumerable<TSource>, Func<TSource, Boolean>)

傳回序列中符合條件的第一個項目;如果找不到這類項目,則傳回預設值。

命名空間:  System.Linq
組件:  System.Core (在 System.Core.dll 中)
public static TSource FirstOrDefault<TSource>(
	this IEnumerable<TSource> source,
	Func<TSource, bool> predicate
)

型別參數

TSource

source 之項目的型別。

參數

source
型別:System.Collections.Generic.IEnumerable<TSource>
傳回項目的 IEnumerable<T>
predicate
型別:System.Func<TSource, Boolean>
用來測試每個項目是否符合條件的函式。

傳回值

型別:TSource
如果 source 是空的,或是沒有任何項目通過 predicate 所指定的測試,則為 default(TSource),否則為 source 中通過 predicate 指定之測試的第一個項目。

使用注意事項

在 Visual Basic 和 C# 中,您可以在任何 IEnumerable<TSource> 型別物件中呼叫這個方法以做為執行個體。使用執行個體方法語法呼叫這個方法時,請省略第一個參數。如需詳細資訊,請參閱擴充方法 (Visual Basic)擴充方法 (C# 程式設計手冊)
例外狀況條件
ArgumentNullException

sourcepredicatenull

參考型別 (Reference Type) 和可為 Null 之型別 (Nullable Type) 的預設值為 null

下列程式碼範例示範如何透過傳入述詞來使用 FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>) 在第二次呼叫方法時,陣列中沒有任何項目符合條件。


            string[] names = { "Hartono, Tommy", "Adams, Terry", 
                                 "Andersen, Henriette Thaulow", 
                                 "Hedlund, Magnus", "Ito, Shu" };

            string firstLongName = names.FirstOrDefault(name => name.Length > 20);

            Console.WriteLine("The first long name is '{0}'.", firstLongName);

            string firstVeryLongName = names.FirstOrDefault(name => name.Length > 30);

            Console.WriteLine(
                "There is {0} name longer than 30 characters.",
                string.IsNullOrEmpty(firstVeryLongName) ? "not a" : "a");

            /*
             This code produces the following output:

             The first long name is 'Andersen, Henriette Thaulow'.
             There is not a name longer than 30 characters.
            */



.NET Framework

支援版本:4、3.5

.NET Framework Client Profile

支援版本:4、3.5 SP1

支援版本:

Windows 7, Windows Vista SP1 (含) 以後版本, Windows XP SP3, Windows Server 2008 (不支援伺服器核心), Windows Server 2008 R2 (SP1 (含) 以後版本支援伺服器核心), Windows Server 2003 SP2

.NET Framework 並不支援各種平台的所有版本。如需支援的版本的清單,請參閱.NET Framework 系統需求
本文對您有任何幫助嗎?
(剩餘 1500 個字元)

社群新增項目

新增
© 2013 Microsoft. 著作權所有,並保留一切權利。