我有一個非常簡單的 .csv 檔案,其中包含 ID 和序列號,實際應用程式不知道有多少行,但總是有兩列
1,16600687 2,16600939 3,16604031 4,16607302
我已經設定了其他所有內容,但我只是將資料加載到一維陣列中,而逗號仍保留在資料中
我得到的結果是第三個位置的字串值是 3,16604031 我如何將它分開,所以它是一個二維陣列,獲取值 [2,0] 為 3,獲取值 [2,1] 為 16604031?
private void button1_Click(object sender, EventArgs e)
{
string stFileNamenPath = "(put location of file here)";
DialogResult result = openFileDialog1.ShowDialog();
StreamReader sr = new StreamReader(stFileNamenPath);
string[] sortArray = null;
while (!sr.EndOfStream)
{
string strResult = sr.ReadToEnd();
sortArray = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
}
string stTest = (string)sortArray.GetValue(2);
MessageBox.Show("string value for 3rd position is " stTest);
}
CSV 檔案
1,16600687
2,16600939
3,16604031
4,16607302
uj5u.com熱心網友回復:
我想到的答案只是一個 LINQ Where 陳述句后跟一個 Select 陳述句。前者用于過濾,第二個用于實際重新映射您擁有的資料。你的代碼會是這樣的
string stFileNamenPath = "(put location of file here)";
//DialogResult result = openFileDialog1.ShowDialog();
StreamReader sr = new StreamReader(stFileNamenPath);
string[] sortArray = null;
while (!sr.EndOfStream)
{
string strResult = sr.ReadToEnd();
sortArray = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
}
char separator = ',';
var mappedArray = sortArray
.Where(x => !string.IsNullOrEmpty(x) && !string.IsNullOrWhiteSpace(x))
.Select(x => new string[] { x.Split(separator)[0], x.Split(separator)[1] }).ToArray();
var stTest = mappedArray[2][1];
MessageBox.Show("string value for 3rd position is " stTest);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/349648.html
