C#找到数组中最短和最长的单词

baz*_*own 2 c# arrays shortest

我试图找到基于长度的最短和最长的字符串值,并且我卡住了.截至目前,脚本在写字线后退出.我认为代码需要一些帮助,我不认为for循环可以自己工作.任何援助将不胜感激.

        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);
    }
Run Code Online (Sandbox Code Playgroud)

Kei*_*las 17

Linq是让你的生活更轻松的方式...

var sorted=word.OrderBy(n => n.Length);
var shortest = sorted.FirstOrDefault();
var longest = sorted.LastOrDefault();
Run Code Online (Sandbox Code Playgroud)

  • +1 表示紧凑性,注意 `O(n log n)` 复杂性(与 Min/Max 的 `O(n)` 不同)。 (2认同)

Dav*_*idN 5

这是您可以使用的通用扩展方法(效率O(n)):

public static class Extensions{
    // assumes that supply a Func<T, int> that will return an int to compare by
    public static Tuple<T, T> MaxMin<T>(this IEnumerable<T> sequence, Func<T, int> propertyAccessor){
        int min = int.MaxValue;
        int max = int.MinValue;

        T maxItem = default(T);
        T minItem = default(T);

        foreach (var i in sequence)
        {
            var propertyValue = propertyAccessor(i);
            if (propertyValue > max){
                max = propertyValue;
                maxItem = i;
            }

            if (propertyValue < min){
                min = propertyValue;
                minItem = i;
            }                       
        }

        return Tuple.Create(maxItem, minItem);
}

// max will be stored in first, min in second
var maxMin = word.MaxMin(s => s.Length);
Run Code Online (Sandbox Code Playgroud)