C# finding the shortest and longest word in a array

baztown picture baztown · Aug 23, 2013 · Viewed 15.8k times · Source

I am trying to find the shortest and longest string value based on length and im getting stuck. As of now the script exits after the writeline. I think the code needs some help, I dont think a for loop can work on its own. Any assistance would be appreciated.

        for (int i = 5; i <0; i++)
        {
            string[] word = new string[5];
           Console.WriteLine("Type in a word");
            word[i] = Console.ReadLine();

             int length = word[i].Length;
             int min = word[0].Length;
             int max = word[0].Length;
             string maxx;
             string minn;


              if (length > max)
                 {
                   maxx = word[i];
                   Console.Write("Shortest");
                  }
             if (length < min) 
              {
                 minn = word[i];
                Console.Write("Longest");
              }



         }
        Console.ReadKey(true);
    }

Answer

Keith Nicholas picture Keith Nicholas · Aug 23, 2013

Linq is the way to go here to make your life a lot easier...

var sorted=word.OrderBy(n => n.Length);
var shortest = sorted.FirstOrDefault();
var longest = sorted.LastOrDefault();