CSV(쉼표로 구분된 값) 파일은 스프레드시트 데이터 또는 행과 열로 표시되는 다른 테이블 형식 데이터를 저장하는 데 자주 사용되는 텍스트 파일입니다. 이 메서드를 Split 사용하여 필드를 구분하면 LINQ를 사용하여 CSV 파일을 쿼리하고 조작하기가 매우 쉽습니다. 실제로 동일한 기술을 사용하여 구조화된 텍스트 줄의 부분 순서를 변경할 수 있습니다. CSV 파일로 제한되지 않습니다.
다음 예제에서는 세 개의 열이 학생의 "성", "이름" 및 "ID"를 나타낸다고 가정합니다. 필드는 학생의 성을 기준으로 사전순으로 표시됩니다. 이 쿼리는 ID 열이 먼저 나타나는 새 시퀀스를 생성한 다음, 학생의 이름과 성을 결합하는 두 번째 열을 생성합니다. 줄의 순서는 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
참고하십시오
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET