共用方式為


LINQ 和集合

大部分的集合都會建立元素序列模型。 您可以使用 LINQ 查詢任何集合型別。 其他 LINQ 方法會尋找集合中的元素、從集合中的元素來計算值,或修改集合或其元素。 這些範例可協助您了解 LINQ 方法,以及如何將它與集合或其他資料來源搭配使用。

如何尋找兩份清單間的集合差異

此範例示範如何使用 LINQ 比較兩個字串清單,並輸出在第一個集合中但不在第二個集合中的字串行。 第一個名稱集合儲存在檔案 names1.txt中:

Bankov, Peter
Holm, Michael
Garcia, Hugo
Potra, Cristina
Noriega, Fabricio
Aw, Kam Foo
Beebe, Ann
Toyoshima, Tim
Guy, Wey Yuan
Garcia, Debra

第二個名稱集合儲存在檔案 names2.txt中。 某些名稱在兩個序列中都會出現。

Liu, Jinghao
Bankov, Peter
Holm, Michael
Garcia, Hugo
Beebe, Ann
Gilchrist, Beth
Myrcha, Jacek
Giakoumakis, Leo
McLin, Nkenge
El Yassir, Mehdi

下列程式碼示範如何使用 Enumerable.Except 方法來尋找在第一個清單中但不在第二個清單中的元素:

// Create the IEnumerable data sources.
string[] names1 = File.ReadAllLines("names1.txt");
string[] names2 = File.ReadAllLines("names2.txt");

// Create the query. Note that method syntax must be used here.
var differenceQuery = names1.Except(names2);

// Execute the query.
Console.WriteLine("The following lines are in names1.txt but not names2.txt");
foreach (string s in differenceQuery)
    Console.WriteLine(s);
/* Output:
 The following lines are in names1.txt but not names2.txt
 Potra, Cristina
 Noriega, Fabricio
 Aw, Kam Foo
 Toyoshima, Tim
 Guy, Wey Yuan
 Garcia, Debra
 */

某些查詢作業型別,例如 ExceptDistinctUnionConcat,只能使用以方法為基礎的語法來表示。

如何合併和比較字串集合

本例示範如何合併包含文字行的檔案,然後排序結果。 具體來說,它會示範如何在這兩組文字行上執行串連、集合聯集和交集。 它會使用與上述範例中所示相同的兩個文字檔。 此程式碼顯示 Enumerable.ConcatEnumerable.UnionEnumerable.Except 的範例。

//Put text files in your solution folder
string[] fileA = File.ReadAllLines("names1.txt");
string[] fileB = File.ReadAllLines("names2.txt");

//Simple concatenation and sort. Duplicates are preserved.
var concatQuery = fileA.Concat(fileB).OrderBy(s => s);

// Pass the query variable to another function for execution.
OutputQueryResults(concatQuery, "Simple concatenate and sort. Duplicates are preserved:");

// Concatenate and remove duplicate names based on
// default string comparer.
var uniqueNamesQuery = fileA.Union(fileB).OrderBy(s => s);
OutputQueryResults(uniqueNamesQuery, "Union removes duplicate names:");

// Find the names that occur in both files (based on
// default string comparer).
var commonNamesQuery = fileA.Intersect(fileB);
OutputQueryResults(commonNamesQuery, "Merge based on intersect:");

// Find the matching fields in each list. Merge the two
// results by using Concat, and then
// sort using the default string comparer.
string nameMatch = "Garcia";

var tempQuery1 = from name in fileA
                 let n = name.Split(',')
                 where n[0] == nameMatch
                 select name;

var tempQuery2 = from name2 in fileB
                 let n2 = name2.Split(',')
                 where n2[0] == nameMatch
                 select name2;

var nameMatchQuery = tempQuery1.Concat(tempQuery2).OrderBy(s => s);
OutputQueryResults(nameMatchQuery, $"""Concat based on partial name match "{nameMatch}":""");

static void OutputQueryResults(IEnumerable<string> query, string message)
{
    Console.WriteLine(Environment.NewLine + message);
    foreach (string item in query)
    {
        Console.WriteLine(item);
    }
    Console.WriteLine($"{query.Count()} total names in list");
}
/* Output:
    Simple concatenate and sort. Duplicates are preserved:
    Aw, Kam Foo
    Bankov, Peter
    Bankov, Peter
    Beebe, Ann
    Beebe, Ann
    El Yassir, Mehdi
    Garcia, Debra
    Garcia, Hugo
    Garcia, Hugo
    Giakoumakis, Leo
    Gilchrist, Beth
    Guy, Wey Yuan
    Holm, Michael
    Holm, Michael
    Liu, Jinghao
    McLin, Nkenge
    Myrcha, Jacek
    Noriega, Fabricio 
    Potra, Cristina
    Toyoshima, Tim
    20 total names in list

    Union removes duplicate names:
    Aw, Kam Foo
    Bankov, Peter
    Beebe, Ann
    El Yassir, Mehdi
    Garcia, Debra
    Garcia, Hugo
    Giakoumakis, Leo
    Gilchrist, Beth
    Guy, Wey Yuan
    Holm, Michael
    Liu, Jinghao
    McLin, Nkenge
    Myrcha, Jacek
    Noriega, Fabricio
    Potra, Cristina
    Toyoshima, Tim
    16 total names in list

    Merge based on intersect:
    Bankov, Peter
    Holm, Michael
    Garcia, Hugo
    Beebe, Ann
    4 total names in list

    Concat based on partial name match "Garcia":
    Garcia, Debra
    Garcia, Hugo
    Garcia, Hugo
    3 total names in list
*/

如何從多個來源填入物件集合

此範例示範如何將不同來源的資料合併成新的類型。

注意

請勿嘗試將記憶體內部資料或檔案系統中的資料,與仍在資料庫中的資料聯結。 這類跨定義域的聯結會產生未定義的結果,因為針對資料庫查詢和其他類型的來源定義聯結作業的方式可能不同。 此外,如果資料庫中的資料量太大,這類作業也可能會導致記憶體不足的例外狀況。 若要將資料庫中的資料聯結至記憶體內部資料,請先在資料庫查詢中呼叫 ToListToArray,然後對傳回的集合執行聯結。

此範例使用兩個檔案。 第一個檔案 names.csv,包含學生名稱和學生識別碼。

Omelchenko,Svetlana,111
O'Donnell,Claire,112
Mortensen,Sven,113
Garcia,Cesar,114
Garcia,Debra,115
Fakhouri,Fadi,116
Feng,Hanying,117
Garcia,Hugo,118
Tucker,Lance,119
Adams,Terry,120
Zabokritski,Eugene,121
Tucker,Michael,122

第二個檔案 scores.csv,包含第一個資料行中的學生識別碼,後面接著測驗分數。

111, 97, 92, 81, 60
112, 75, 84, 91, 39
113, 88, 94, 65, 91
114, 97, 89, 85, 82
115, 35, 72, 91, 70
116, 99, 86, 90, 94
117, 93, 92, 80, 87
118, 92, 90, 83, 78
119, 68, 79, 88, 92
120, 99, 82, 81, 79
121, 96, 85, 91, 60
122, 94, 92, 91, 91

下列範例示範如何使用具名列 Student 儲存從兩個記憶體內部字串集合合併得來的資料,這些字串模擬 .csv 格式的試算表資料。 識別碼是用來將學生對應至其分數的索引碼。

// Each line of names.csv consists of a last name, a first name, and an
// ID number, separated by commas. For example, Omelchenko,Svetlana,111
string[] names = File.ReadAllLines("names.csv");

// Each line of scores.csv consists of an ID number and four test
// scores, separated by commas. For example, 111, 97, 92, 81, 60
string[] scores = File.ReadAllLines("scores.csv");

// Merge the data sources using a named type.
// var could be used instead of an explicit type. Note the dynamic
// creation of a list of ints for the ExamScores member. The first item
// is skipped in the split string because it is the student ID,
// not an exam score.
IEnumerable<Student> queryNamesScores = from nameLine in names
                                        let splitName = nameLine.Split(',')
                                        from scoreLine in scores
                                        let splitScoreLine = scoreLine.Split(',')
                                        where Convert.ToInt32(splitName[2]) == Convert.ToInt32(splitScoreLine[0])
                                        select new Student
                                        (
                                            FirstName: splitName[0],
                                            LastName: splitName[1],
                                            ID: Convert.ToInt32(splitName[2]),
                                            ExamScores: (from scoreAsText in splitScoreLine.Skip(1)
                                                         select Convert.ToInt32(scoreAsText)
                                                        ).ToArray()
                                        );

// Optional. Store the newly created student objects in memory
// for faster access in future queries. This could be useful with
// very large data files.
List<Student> students = queryNamesScores.ToList();

// Display each student's name and exam score average.
foreach (var student in students)
{
    Console.WriteLine($"The average score of {student.FirstName} {student.LastName} is {student.ExamScores.Average()}.");
}
/* Output:
The average score of Omelchenko Svetlana is 82.5.
The average score of O'Donnell Claire is 72.25.
The average score of Mortensen Sven is 84.5.
The average score of Garcia Cesar is 88.25.
The average score of Garcia Debra is 67.
The average score of Fakhouri Fadi is 92.25.
The average score of Feng Hanying is 88.
The average score of Garcia Hugo is 85.75.
The average score of Tucker Lance is 81.75.
The average score of Adams Terry is 85.25.
The average score of Zabokritski Eugene is 83.
The average score of Tucker Michael is 92.
*/

select 子句中,每個新的 Student 物件都會從兩個來源中的資料初始化。

如果您不需要儲存查詢的結果,則元組或匿名型別會比具名型別更方便使用。 下列範例會執行與上述範例相同的工作,但使用元組而不是具名型別:

// Merge the data sources by using an anonymous type.
// Note the dynamic creation of a list of ints for the
// ExamScores member. We skip 1 because the first string
// in the array is the student ID, not an exam score.
var queryNamesScores2 = from nameLine in names
                        let splitName = nameLine.Split(',')
                        from scoreLine in scores
                        let splitScoreLine = scoreLine.Split(',')
                        where Convert.ToInt32(splitName[2]) == Convert.ToInt32(splitScoreLine[0])
                        select (FirstName: splitName[0], 
                                LastName: splitName[1], 
                                ExamScores: (from scoreAsText in splitScoreLine.Skip(1)
                                             select Convert.ToInt32(scoreAsText))
                                             .ToList()
                               );

// Display each student's name and exam score average.
foreach (var student in queryNamesScores2)
{
    Console.WriteLine($"The average score of {student.FirstName} {student.LastName} is {student.ExamScores.Average()}.");
}

如何使用 LINQ 查詢 ArrayList

使用 LINQ 查詢非泛型 IEnumerable 集合 (例如 ArrayList) 時,您必須明確宣告範圍變數的型別,以反映集合中物件的特定型別。 如果您有 Student 物件的 ArrayList,您的 from 子句看起來應該如下:

var query = from Student s in arrList
//...

藉由指定範圍變數的型別,您可以將 ArrayList 中的每個項目強制型轉為 Student

在查詢運算式中使用具有明確類型的範圍變數,相當於呼叫 Cast 方法。 如果無法執行指定的強制型轉,則 Cast 會擲回例外狀況。 CastOfType 是兩種在非泛型 IEnumerable 型別上運作的標準查詢運算子方法。 如需詳細資訊,請參閱 LINQ 查詢作業中的類型關聯性。 下列範例顯示 ArrayList 的查詢。

ArrayList arrList = new ArrayList();
arrList.Add(
    new Student
    (
        FirstName: "Svetlana",
        LastName: "Omelchenko",
        ExamScores: new int[] { 98, 92, 81, 60 }
    ));
arrList.Add(
    new Student
    (
        FirstName: "Claire",
        LastName: "O’Donnell",
        ExamScores: new int[] { 75, 84, 91, 39 }
    ));
arrList.Add(
    new Student
    (
        FirstName: "Sven",
        LastName: "Mortensen",
        ExamScores: new int[] { 88, 94, 65, 91 }
    ));
arrList.Add(
    new Student
    (
        FirstName: "Cesar",
        LastName: "Garcia",
        ExamScores: new int[] { 97, 89, 85, 82 }
    ));

var query = from Student student in arrList
            where student.ExamScores[0] > 95
            select student;

foreach (Student s in query)
    Console.WriteLine(s.LastName + ": " + s.ExamScores[0]);