逗號分隔值 (CSV) 檔案是文字檔,通常用來儲存電子表格數據或其他以數據列和數據行表示的表格式數據。 藉由使用 Split 方法來分隔欄位,可以很輕鬆地使用LINQ查詢及操作CSV檔案。 事實上,相同的技術可以用來重新排列任何結構化文字行的部分:不限於 CSV 檔案。
在下列範例中,假設這三個數據行代表學生的「姓氏」、「名字」和「標識碼」。這些欄位會根據學生的姓氏依字母順序排列。 查詢會產生一個新的順序,其中識別碼欄位首先出現,接著是第二個欄位,結合學生的名字和姓氏。 這些行會根據 [ID] 欄位重新排序。 結果會儲存到新的檔案中,而且不會修改原始數據。
若要建立數據檔
將下列幾行複製到名為 spreadsheet1.csv的純文字檔案中。 將檔案儲存在您的項目資料夾中。
Adams,Terry,120 Fakhouri,Fadi,116 Feng,Hanying,117 Garcia,Cesar,114 Garcia,Debra,115 Garcia,Hugo,118 Mortensen,Sven,113 O'Donnell,Claire,112 Omelchenko,Svetlana,111 Tucker,Lance,119 Tucker,Michael,122 Zabokritski,Eugene,121
範例
Class CSVFiles
Shared Sub Main()
' Create the IEnumerable data source.
Dim lines As String() = System.IO.File.ReadAllLines("../../../spreadsheet1.csv")
' Execute the query. Put field 2 first, then
' reverse and combine fields 0 and 1 from the old field
Dim lineQuery = From line In lines
Let x = line.Split(New Char() {","})
Order By x(2)
Select x(2) & ", " & (x(1) & " " & x(0))
' Execute the query and write out the new file. Note that WriteAllLines
' takes a string array, so ToArray is called on the query.
System.IO.File.WriteAllLines("../../../spreadsheet2.csv", lineQuery.ToArray())
' Keep console window open in debug mode.
Console.WriteLine("Spreadsheet2.csv written to disk. Press any key to exit")
Console.ReadKey()
End Sub
End Class
' Output to spreadsheet2.csv:
' 111, Svetlana Omelchenko
' 112, Claire O'Donnell
' 113, Sven Mortensen
' 114, Cesar Garcia
' 115, Debra Garcia
' 116, Fadi Fakhouri
' 117, Hanying Feng
' 118, Hugo Garcia
' 119, Lance Tucker
' 120, Terry Adams
' 121, Eugene Zabokritski
' 122, Michael Tucker