At the bottom is the line readbyline from txt file and the words are split by space between them ( " "
) how do I sort and return the length from the smallest to the largest?
This is what I have now - click on the link:
The code
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);
}
}
Use Linq and you will get Min and max length, like below.
var min = words.Split(' ').Min(s => s.Length);
var max = words.Split(' ').Max(s => s.Length);
If you need all words by Sorted then use below.
var sortedList = words.Split(' ').Select(s=>new {Word=s,WordLength=s.Length }).OrderBy(o=>o.WordLength);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.