我正在研究一个按字母长度排序字典单词的程序。当前代码输出结果。我将结果保存为文本文件时遇到问题。
当前代码
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;
}
}
答案 0 :(得分:0)
我想你想要File.WriteAllLiness(filePath, SortByLength(linesList));
请注意,您的代码可以简化,因为没有理由像您一样初始化linesList
。你可以这样做:
string[] fileContent = File.ReadAllLines(filePath);
var linesList = SortByLength(fileContent);
foreach (string s in lineslist)
{
//...
}
File.WriteAllLines(filePath, linesList);