6

I need to provide a solution to find the shortest string in an array of string. I was thinking that it should be compare the length of each string in order to return.

This is where I was stuck

static void Main(string[] args)
{
    //find the shortest string in an array of string
    string[] names = new string[3]{
        "Tom", "and", "jerry"
    };

    foreach(string name in names){
        Console.Write(name + ", ");
    }

    Console.ReadKey();
}

Can anyone help me with the compare part and explain it

3
  • everyone...yeahh thats exactly how you get help here... Commented Jun 23, 2017 at 9:56
  • What result do you expect in your example because "Tom" and "and" have the same length? Commented Jun 23, 2017 at 9:59
  • 2
    which would you class as the shortest string, "Tom" or "and"? what have you tried? Commented Jun 23, 2017 at 9:59

9 Answers 9

15

this one will find the first shortest string without sorting the collection:

int minLength = names.Min(y=>y.Length); // this gets you the shortest length of all elements in names
string shortest = names.FirstOrDefault(x=>x.Length == minLength);

Explanation: it will check for that element which length is equal to the smallest length in the entire collection.

EDIT:

Can anyone help me with the compare part and explain it

To compare the length of a string use the Length property and the == operator. You can do this of course also in a loop as ChoockY did.

Sign up to request clarification or add additional context in comments.

Comments

10

Use LINQ:

var shortestString = names.OrderBy(c => c.Length).FirstOrDefault();

3 Comments

Sorting is slower than simple linear search.
@adjan This is not a good reason for someone to downvote. Downvotes are for really bad try or incorrect answeres!!
Personally I didn't downwote you, because your answer technically does what the OP is asking for. But as already pointed out sorting is a waste of time in this case. I certainly wouldn't recommend it, especially to a novice. A downvote is entirely justifiable.
4

you can do this wiht linq,

var shortestName = names.OrderBy(name => name.Length).FirstOrDefault();

or

string shortestName = names.Aggregate((a1, a2) => a1.Length <a2.Length ? a1 : a2);

1 Comment

This would end in an exception if there are no entries in the nameslist. I would use FirstOrDefaultinstead.
2

You can use LINQ, as the others say. This is the easiest way to do the job, but i think, you should learn some algorithms. Finding the minimum/maximum value in an array belongs to programming basics.

Here can you read about it: http://www.stoimen.com/blog/2012/05/21/computer-algorithms-minimum-and-maximum/

The pure c# impementation looks like:

string[] names = new string[3]{
     "Tom", "and", "jerry"
};

string minValue = names[0];
foreach (string name in names)
{
     if (name.Length < minValue.Length)
     {
          minValue = name;
     }
}

Console.WriteLine(minValue);

2 Comments

Agreed. Plus, I might add, sorting is a useless waste of time in this case.
Thank you, It worked, I was stuck at the finding max/min part but you saved me, and thanks to everyone helped.
2

You can use MaxBy for this. And please PLEASE do not sort the entire sequence just to find maximum. This is very wasteful, intentional wasting is the cancer that would kill performance of your software.

2 Comments

Perhaps MinBy would be better?
@MartinMulder You are right, thank you. I tend to use only MaxBy and flip sign when necessary, but you are right.
2

Nobody's provided the answer in a one-liner that runs in O(N) time. A better solution is to use .Aggregate:

var shortest = names.Aggregate((s, best) => s.Length < best.Length ? s : best)

2 Comments

It was already proposed here: stackoverflow.com/a/44718531/7034621
Not all that glitters is gold. This is more memory intensive as compared to having a function returning the min value with basic comparison as also suggested by @ChoockY
0

Maybe you can do this:

string[] names = new string[3]{
 "Tom", "and", "jerry"
};
var query = from n in names select n.Length;
Console.WriteLine("Shortest name: " + names[Array.IndexOf(query.ToArray(), query.ToArray().Min())]);

I hope this can be useful to someone

Comments

0

Write your own Linq, like this:

public static T1 Min<T1, T2>(this IEnumerable<T1> source, Func<T1, T2> selector) where T2 : IComparable<T2> {
    if (source == null) {
        throw new ArgumentNullException(nameof(source));
    }

    if (selector == null) {
        throw new ArgumentNullException(nameof(selector));
    }

    bool firstIteration = true;

    T2 minimum = default;
    T1 value = default;

    foreach (T1 v in source) {
        T2 current = selector.Invoke(v);

        if (current == null) {
            throw new NullReferenceException();
        }

        if (firstIteration || current.CompareTo(minimum) < 0) {
            minimum = current;
            value = v;
            firstIteration = false;
        }
    }

    return value;
}

These variable names are bad. It is up to you to improve them.

Comments

0
            string[] countries = { "UK", "USA", "INDIA" };

            int? result = null;
            string nameOfCountry = string.Empty;
            foreach (var country in countries)
            {
                if (result == null || country.Length < result)
                {
                    nameOfCountry = country;
                    result = country.Length;
                }
            }
             

            Console.WriteLine(nameOfCountry);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.