共用方式為


HOW TO:重新排列有分隔符號的檔案中的欄位 (LINQ)

更新:2007 年 11 月

逗號分隔值 (CSV) 檔案是一種文字檔,常用來儲存試算表資料或其他以資料列和資料行呈現的表格式資料。使用 Split 方法隔開欄位後,就可以利用 LINQ 輕鬆地查詢和管理 CSV 檔案。實際上,相同的技巧可以用在重新排列任何結構化文字行中的部分,而且不限為 CSV 檔案。

在下列範例中,假設有三個資料行分別表示學生的「姓氏」、「名字」和「學號」。欄位是按照學生的姓氏字母排序。這個查詢產生的新序列會先出現學號資料行,而後面接著的第二個資料行則結合了學生的姓氏和名字。這些行會根據 ID 欄位重新排列。結果會儲存至新的檔案,並不會修改原始資料。

若要建立資料檔案

  • 建立新的 Visual C# 或 Visual Basic 專案,然後將下列各行複製名為 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
class CSVFiles
{
    static void Main(string[] args)
    {
        // Create the IEnumerable data source
        string[] lines = System.IO.File.ReadAllLines(@"../../../spreadsheet1.csv");

        // Create the query. Put field 2 first, then
        // reverse and combine fields 0 and 1 from the old field
        IEnumerable<string> query =
            from line in lines
            let x = line.Split(',')
            orderby x[2]
            select x[2] + ", " + (x[1] + " " + x[0]);

        // Execute the query and write out the new file. Note that WriteAllLines
        // takes a string[], so ToArray is called on the query.
        System.IO.File.WriteAllLines(@"../../../spreadsheet2.csv", query.ToArray());

        Console.WriteLine("Spreadsheet2.csv written to disk. Press any key to exit");
        Console.ReadKey();
    }
}
/* 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
 */

編譯程式碼

  • 建立以 .NET Framework 3.5 版為目標的 Visual Studio 專案。專案預設會含 System.Core.dll 的參考,以及 System.Linq 命名空間 (Namespace) 的 using 指示詞 (C#) 或 Imports 陳述式 (Visual Basic)。請在 C# 專案中,加入 System.IO 命名空間的 using 指示詞。

  • 將此程式碼複製至您的專案。

  • 按 F5 編譯和執行程式。

  • 按任何鍵離開主控台視窗。

請參閱

工作

HOW TO:從 CSV 檔案產生 XML

概念

LINQ 和字串

LINQ 和檔案目錄