구분 문자열을 목록으로 분할()하는 방법
내 코드는 다음과 같습니다.
String[] lineElements;
. . .
try
{
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
lineElements = line.Split(',');
. . .
대신 리스트를 써야겠다고 생각했어요하지만 이 코드는:
List<String> listStrLineElements;
. . .
try
{
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
listStrLineElements = line.Split(',');
. . .
...라는 메시지가 나타납니다. "'string[]' 유형을 'System'으로 암시적으로 변환할 수 없습니다.컬렉션.일반적인.리스트'
string.Split()
배열을 반환합니다. 다음을 사용하여 목록으로 변환할 수 있습니다.ToList()
:
listStrLineElements = line.Split(',').ToList();
가져올 필요가 있습니다.System.Linq
에 액세스하기 위해.ToList()
기능.
다음 중 하나를 선택합니다.
List<string> list = new List<string>(array);
또는 LINQ에서:
List<string> list = array.ToList();
또는 특정 구현에 의존하지 않도록 코드를 변경합니다.
IList<string> list = array; // string[] implements IList<string>
네임스페이스 사용 포함System.Linq
List<string> stringList = line.Split(',').ToList();
각 항목을 반복할 때 쉽게 사용할 수 있습니다.
foreach(string str in stringList)
{
}
String.Split()
배열을 반환하므로 다음을 사용하여 목록으로 변환합니다.ToList()
그냥 사용할 수 있습니다.using System.Linq;
List<string> stringList = line.Split(',') // this is array
.ToList(); // this is a list which you can loop in all split string
다음 행을 사용해 보십시오.
List<string> stringList = line.Split(',').ToList();
이것은 csv 파일을 읽을 것이고 이중 따옴표를 처리하는 csv 줄 분할기를 포함하며 엑셀이 열려 있더라도 읽을 수 있습니다.
public List<Dictionary<string, string>> LoadCsvAsDictionary(string path)
{
var result = new List<Dictionary<string, string>>();
var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
System.IO.StreamReader file = new System.IO.StreamReader(fs);
string line;
int n = 0;
List<string> columns = null;
while ((line = file.ReadLine()) != null)
{
var values = SplitCsv(line);
if (n == 0)
{
columns = values;
}
else
{
var dict = new Dictionary<string, string>();
for (int i = 0; i < columns.Count; i++)
if (i < values.Count)
dict.Add(columns[i], values[i]);
result.Add(dict);
}
n++;
}
file.Close();
return result;
}
private List<string> SplitCsv(string csv)
{
var values = new List<string>();
int last = -1;
bool inQuotes = false;
int n = 0;
while (n < csv.Length)
{
switch (csv[n])
{
case '"':
inQuotes = !inQuotes;
break;
case ',':
if (!inQuotes)
{
values.Add(csv.Substring(last + 1, (n - last)).Trim(' ', ','));
last = n;
}
break;
}
n++;
}
if (last != csv.Length - 1)
values.Add(csv.Substring(last + 1).Trim());
return values;
}
string[] thisArray = myString.Split('/');//<string1/string2/string3/--->
List<string> myList = new List<string>(); //make a new string list
myList.AddRange(thisArray);
사용하다AddRange
지나가기 위해string[]
문자열 목록을 가져옵니다.
이 확장 방법을 사용하여 다음을 처리합니다.null
입력하고 중복된 공백도 제거합니다.
public static List<string> CsvToList(this string csv)
{
if (string.IsNullOrEmpty(csv))
{
return new List<string>();
}
return csv.Split(',').Select(item => item.Trim()).ToList();
}
입력 CSV가 "Apple, Orange, Pear"인 경우 쉼표 뒤의 공백을 제거합니다.
이 var country처럼 사용할 수 있습니다.DBs="myDB,ukDB";
시골DBsList = countryDBs.분할(',',')받는 사람();
foreach (var countryDB in countryDBsList)
{
}
언급URL : https://stackoverflow.com/questions/9263695/how-to-split-a-delimited-string-to-a-liststring
'programing' 카테고리의 다른 글
데이터 액세스 후 C#에서 Excel 응용 프로그램 프로세스 닫기 (0) | 2023.05.02 |
---|---|
에레독 배관을 위한 다중 라인 구문; 이것은 휴대 가능합니까? (0) | 2023.05.02 |
데이터 입력 후 문자열을 트리밍하는 가장 좋은 방법입니다.사용자 정의 모델 바인더를 작성해야 합니까? (0) | 2023.05.02 |
MongoDB에서 참조된 개체를 쿼리하려면 어떻게 해야 합니까? (0) | 2023.05.02 |
PostgreSQL에서 상속된 테이블을 사용해야 하는 경우 (0) | 2023.05.02 |