在底部是txt文件的readbyline行,并且单词之间用空格隔开(" "
)如何排序并从最小到最大返回长度?
这是我现在拥有的-单击链接:
代码
if (System.IO.File.Exists(textFile))
{
using (System.IO.StreamReader file = new System.IO.StreamReader(textFile))
{
int counter = 0;
string words;
string[] line;
while ((words = file.ReadLine()) != null)
{
line = Regex.Split(words, " ");
foreach (string line_1 in line)
{
Console.WriteLine(line_1 + " " + line_1.Length);
}
Console.WriteLine(" ");
counter++;
Console.WriteLine("Line[{1}]: {0}\n", words, counter);
}
file.Close();
Console.WriteLine(" ");
Console.WriteLine("File has [{0}] Lines.", counter);
}
}
使用Linq,您将获得最小和最大长度,如下所示。
var min = words.Split(' ').Min(s => s.Length);
var max = words.Split(' ').Max(s => s.Length);
如果需要所有单词按排序,则在下面使用。
var sortedList = words.Split(' ').Select(s=>new {Word=s,WordLength=s.Length }).OrderBy(o=>o.WordLength);