C# - 将输出写入文本文件
C# - Write output into a text file
我正在开发一个按长度对字典单词进行排序的程序。当前代码输出结果。我无法将结果保存为文本文件。
当前代码
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Initialize a List of strings.
string filePath = "text.txt";
List<string> linesList = new List<string>();
string[] fileContent = System.IO.File.ReadAllLines(filePath);
linesList.AddRange(fileContent);
// Send the List to the method.
foreach (string s in SortByLength(linesList))
{
Console.WriteLine(s);
}
System.IO.File.WriteAllLines("solution.txt",sorted);
}
static IEnumerable<string> SortByLength(IEnumerable<string> e)
{
// Use LINQ to sort the array received and return a copy.
var sorted = from s in e
orderby s.Length ascending
select s;
return sorted;
}
}
我想你想要File.WriteAllLiness(filePath, SortByLength(linesList));
请注意,您的代码可以简化,因为没有理由像您一样初始化 linesList
。你可以这样做:
string[] fileContent = File.ReadAllLines(filePath);
var linesList = SortByLength(fileContent);
foreach (string s in lineslist)
{
//...
}
File.WriteAllLines(filePath, linesList);
我正在开发一个按长度对字典单词进行排序的程序。当前代码输出结果。我无法将结果保存为文本文件。
当前代码
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Initialize a List of strings.
string filePath = "text.txt";
List<string> linesList = new List<string>();
string[] fileContent = System.IO.File.ReadAllLines(filePath);
linesList.AddRange(fileContent);
// Send the List to the method.
foreach (string s in SortByLength(linesList))
{
Console.WriteLine(s);
}
System.IO.File.WriteAllLines("solution.txt",sorted);
}
static IEnumerable<string> SortByLength(IEnumerable<string> e)
{
// Use LINQ to sort the array received and return a copy.
var sorted = from s in e
orderby s.Length ascending
select s;
return sorted;
}
}
我想你想要File.WriteAllLiness(filePath, SortByLength(linesList));
请注意,您的代码可以简化,因为没有理由像您一样初始化 linesList
。你可以这样做:
string[] fileContent = File.ReadAllLines(filePath);
var linesList = SortByLength(fileContent);
foreach (string s in lineslist)
{
//...
}
File.WriteAllLines(filePath, linesList);