HOW TO:從不同的檔案聯結內容 (LINQ)
這個範例示範如何將兩個逗號分隔檔案中資料的共同值當做相符的索引鍵,聯結這兩個檔案中的資料。如果您需要將兩個試算表的資料,或一個試算表和一個不同格式之檔案中的資料合併為新的檔案,則這項技巧十分有用。您可以修改這個範例,將它運用於任何種類的結構化文字。
若要建立資料檔
將下列各行複製到名為 scores.csv 的檔案,並將該檔案儲存至與專案檔相同的資料夾中。例如,如果您的專案檔位於 Visual Studio 2010\Projects,則將 scores.csv 儲存至該資料夾。此檔案代表試算表資料。第 1 行是學生的學號,而第 2 到 5 行則是測驗分數。
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
將下列各行複製到名為 names.csv 的檔案,並將該檔案儲存至與專案檔相同的資料夾中。例如,如果您的專案檔位於 Visual Studio 2010\Projects,則將 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
範例
Class JoinStrings
Shared Sub Main()
' Join content from spreadsheet files that contain
' related information. names.csv contains the student name
' plus an ID number. scores.csv contains the ID and a
' set of four test scores. The following query joins
' the scores to the student names by using ID as a
' matching key.
Dim names As String() = System.IO.File.ReadAllLines("../../../names.csv")
Dim scores As String() = System.IO.File.ReadAllLines("../../../scores.csv")
' Name: Last[0], First[1], ID[2], Grade Level[3]
' Omelchenko, Svetlana, 111, 2
' Score: StudentID[0], Exam1[1] Exam2[2], Exam3[3], Exam4[4]
' 111, 97, 92, 81, 60
' This query joins two dissimilar spreadsheets based on common ID value.
' Multiple from clauses are used instead of a join clause
' in order to store results of id.Split.
Dim scoreQuery1 = From name In names
Let n = name.Split(New Char() {","})
From id In scores
Let n2 = id.Split(New Char() {","})
Where n(2) = n2(0)
Select n(0) & "," & n(1) & "," & n2(0) & "," & n2(1) & "," &
n2(2) & "," & n2(3)
' Pass a query variable to a Sub and execute it there.
' The query itself is unchanged.
OutputQueryResults(scoreQuery1, "Merge two spreadsheets:")
' Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.")
Console.ReadKey()
End Sub
Shared Sub OutputQueryResults(ByVal query As IEnumerable(Of String), ByVal message As String)
Console.WriteLine(System.Environment.NewLine & message)
For Each item As String In query
Console.WriteLine(item)
Next
Console.WriteLine(query.Count & " total names in list")
End Sub
End Class
' Output:
'Merge two spreadsheets:
'Adams,Terry,120, 99, 82, 81
'Fakhouri,Fadi,116, 99, 86, 90
'Feng,Hanying,117, 93, 92, 80
'Garcia,Cesar,114, 97, 89, 85
'Garcia,Debra,115, 35, 72, 91
'Garcia,Hugo,118, 92, 90, 83
'Mortensen,Sven,113, 88, 94, 65
'O'Donnell,Claire,112, 75, 84, 91
'Omelchenko,Svetlana,111, 97, 92, 81
'Tucker,Lance,119, 68, 79, 88
'Tucker,Michael,122, 94, 92, 91
'Zabokritski,Eugene,121, 96, 85, 91
'12 total names in list
class JoinStrings
{
static void Main()
{
// Join content from dissimilar files that contain
// related information. File names.csv contains the student
// name plus an ID number. File scores.csv contains the ID
// and a set of four test scores. The following query joins
// the scores to the student names by using ID as a
// matching key.
string[] names = System.IO.File.ReadAllLines(@"../../../names.csv");
string[] scores = System.IO.File.ReadAllLines(@"../../../scores.csv");
// Name: Last[0], First[1], ID[2]
// Omelchenko, Svetlana, 11
// Score: StudentID[0], Exam1[1] Exam2[2], Exam3[3], Exam4[4]
// 111, 97, 92, 81, 60
// This query joins two dissimilar spreadsheets based on common ID value.
// Multiple from clauses are used instead of a join clause
// in order to store results of id.Split.
IEnumerable<string> scoreQuery1 =
from name in names
let nameFields = name.Split(',')
from id in scores
let scoreFields = id.Split(',')
where nameFields[2] == scoreFields[0]
select nameFields[0] + "," + scoreFields[1] + "," + scoreFields[2]
+ "," + scoreFields[3] + "," + scoreFields[4];
// Pass a query variable to a method and execute it
// in the method. The query itself is unchanged.
OutputQueryResults(scoreQuery1, "Merge two spreadsheets:");
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
static void OutputQueryResults(IEnumerable<string> query, string message)
{
Console.WriteLine(System.Environment.NewLine + message);
foreach (string item in query)
{
Console.WriteLine(item);
}
Console.WriteLine("{0} total names in list", query.Count());
}
}
/* Output:
Merge two spreadsheets:
Adams, 99, 82, 81, 79
Fakhouri, 99, 86, 90, 94
Feng, 93, 92, 80, 87
Garcia, 97, 89, 85, 82
Garcia, 35, 72, 91, 70
Garcia, 92, 90, 83, 78
Mortensen, 88, 94, 65, 91
O'Donnell, 75, 84, 91, 39
Omelchenko, 97, 92, 81, 60
Tucker, 68, 79, 88, 92
Tucker, 94, 92, 91, 91
Zabokritski, 96, 85, 91, 60
12 total names in list
*/
編譯程式碼
建立以 .NET Framework 3.5 (含) 以後版本為目標的 Visual Studio 專案。專案預設會含 System.Core.dll 的參考,以及 System.Linq 命名空間 (Namespace) 的 using 指示詞 (C#) 或 Imports 陳述式 (Visual Basic)。請在 C# 專案中,加入 System.IO 命名空間的 using 指示詞。
請將這段程式碼複製到您的專案,
按 F5 編譯和執行程式。
按任何鍵離開主控台視窗。