使用 LINQ 篩選 C# 中的資料

篩選指的是將結果集限制為只包含符合指定條件之元素的作業, 這也稱為選取符合指定條件的元素。

下圖顯示字元序列的篩選結果。 篩選作業的述詞指定字元必須為 'A'。

顯示 LINQ 篩選作業的圖表

下表列出可執行選取的標準查詢運算子方法:

方法名稱 描述 C# 查詢運算式語法 相關資訊
OfType 根據可轉換為所指定類型的能力來選取值。 不適用。 Enumerable.OfType

Queryable.OfType
其中 根據述詞函式來選取值。 where Enumerable.Where

Queryable.Where

下列範例使用 where 子句從陣列篩選出具有特定長度的字串。

string[] words = ["the", "quick", "brown", "fox", "jumps"];

IEnumerable<string> query = from word in words
                            where word.Length == 3
                            select word;

foreach (string str in query)
{
    Console.WriteLine(str);
}

/* This code produces the following output:

    the
    fox
*/

使用方法語法的對等查詢會顯示在下列程式碼中:

string[] words = ["the", "quick", "brown", "fox", "jumps"];

IEnumerable<string> query =
    words.Where(word => word.Length == 3);

foreach (string str in query)
{
    Console.WriteLine(str);
}

/* This code produces the following output:

    the
    fox
*/

另請參閱