如何从最小的C#到最大的C#获取字符串的长度

问题描述 投票:0回答:1

在底部是txt文件的readbyline行,并且单词之间用空格隔开(" ")如何排序并从最小到最大返回长度?

这是我现在拥有的-单击链接:

link to the picture

代码

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);
    }
} 
c# arrays console streamreader string-length
1个回答
0
投票

使用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);
© www.soinside.com 2019 - 2024. All rights reserved.