C# finding the shortest and longest word in a array

后端 未结 8 1263
小蘑菇
小蘑菇 2021-01-15 04:32

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 h

8条回答
  •  感情败类
    2021-01-15 04:59

    Here's a generic extension method you can use (efficiency O(n)):

    public static class Extensions{
        // assumes that supply a Func that will return an int to compare by
        public static Tuple MaxMin(this IEnumerable sequence, Func 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);
    

提交回复
热议问题