次の方法で共有


方法 : 区切り記号入りファイルのフィールドの順序を変更する (LINQ)

更新 : 2007 年 11 月

コンマ区切り値 (CSV) ファイルはテキスト ファイルの一種であり、行と列で表されるスプレッドシートのデータ、または他の表形式のデータを格納するためによく使用されます。Split メソッドを使用して各フィールドを切り離すと、LINQ を使用して非常に簡単に CSV ファイルを照会および操作できます。実際には、同じ方法を使用して、CSV ファイルに限らず任意の構造化されたテキスト行の構成部分の順序を変更できます。

次の例では、3 つの列が生徒の "姓"、"名"、および "ID" を表していると仮定します。これらのフィールドは、生徒の姓を基準にアルファベット順で並べられています。クエリの結果として、新しいシーケンスが生成されます。このシーケンスでは、ID 列が最初にあり、生徒の姓と名を結合した列がその後に続きます。行の順序は、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 Version 3.5 を対象とする Visual Studio プロジェクトを作成します。プロジェクトには、System.Core.dll への参照と、System.Linq 名前空間に対する using ディレクティブ (C#) または Imports ステートメント (Visual Basic) が既定で含まれます。C# プロジェクトでは、System.IO 名前空間に対する using ディレクティブを追加します。

  • このコードをプロジェクト内にコピーします。

  • F5 キーを押して、プログラムをコンパイルおよび実行します。

  • 任意のキーを押して、コンソール ウィンドウを終了します。

参照

処理手順

方法 : CSV ファイルから XML を生成する

概念

LINQ と文字列

LINQ とファイル ディレクトリ