如何使它成為一個 int 陣列,而不是一個字串陣列?由于我是初學者程式員,因此我將其視為挑戰。
static void Main(string[] args)
{
string [] lines = System.IO.File.ReadAllLines(@"input.txt"); // <- make this an int array instead.
// Display the file contents by using a foreach loop.
System.Console.WriteLine("Contents of input.txt = ");
foreach (string line in lines)
{
// Use a tab to indent each line of the file.
Console.WriteLine("\t" line);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
// Wait before closing
Console.ReadKey();
}
uj5u.com熱心網友回復:
您可以使用Select來映射集合的值。
int[] = File.ReadAllLines("c:/myFile.txt")
.Select(x => int.Parse(x))
.ToArray()
這是一個較短的“無點”樣式語法:
int[] = File.ReadAllLines("c:/myFile.txt")
.Select(int.Parse)
.ToArray()
uj5u.com熱心網友回復:
我認為您正在尋找 int.Parse(string)。它將嘗試將字串轉換為 int,如果無法完成則拋出錯誤。還有另一個稱為 TryParse() 的版本,它回傳一本書以檢查是否成功,以進行您自己的錯誤處理。
您只需遍歷您的行陣列并將決議的 int 復制到一個 int 陣列中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/497090.html
上一篇:os.walk查找不存在的檔案
