다음을 통해 공유


방법: 구분된 파일의 필드 다시 정렬(LINQ)

업데이트: 2007년 11월

쉼표로 구분된 값(CSV) 파일은 스프레드시트 데이터 또는 행 및 열로 표현되는 다른 테이블 형식 데이터를 저장하는 데 자주 사용되는 텍스트 파일입니다. Split 메서드를 사용하여 필드를 구분하면 LINQ를 사용하여 CSV 파일을 쿼리하고 조작하기가 매우 쉬워집니다. 사실 같은 기술을 사용하여 구조화된 텍스트 줄의 부분을 다시 정렬할 수 있으며 이 기술은 CSV 파일로 제한되지는 않습니다.

다음 예제에서는 세 개의 열이 각각 학생의 "성", "이름" 및 "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 버전 3.5를 대상으로 하는 Visual Studio 프로젝트를 만듭니다. 기본적으로 프로젝트에는 System.Core.dll에 대한 참조 및 System.Linq 네임스페이스에 대한 using 지시문(C#) 또는 Imports 문(Visual Basic)이 있습니다. C# 프로젝트에서는 System.IO 네임스페이스에 대한 using 지시문을 추가합니다.

  • 프로젝트에 이 코드를 복사합니다.

  • F5 키를 눌러 프로그램을 컴파일하고 실행합니다.

  • 아무 키나 눌러 콘솔 창을 닫습니다.

참고 항목

작업

방법: CSV 파일에서 XML 생성

개념

LINQ 및 문자열

LINQ 및 파일 디렉터리