Click here to Skip to main content
15,898,538 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
string[] test = { "absc", "abc", "abcder", "abcdg" };


how to find the index value of array whose element length is minimum in c#


Here i should get 1 as a output




Thanks In advance.

What I have tried:

<pre>string[] test = { "absc", "abc", "abcder", "abcdg" };


how to find the index value of array whose element length is minimum in c#


Here i should get 1 as a output




Thanks In advance.
Posted
Updated 13-May-17 21:43pm
Comments
CHill60 14-May-17 0:54am    
The "What I have tried" section is for you to put the code that you have tried.

This isn't difficult, but ... it smells of homework so I'll give you no code!

All you need to do is:
1) Create two variables: minLength (defaulted to int.MaxValue) and minIndex (defaulted to -1)
2) use a for loop to look at all elements in your array with a index variable that runs from 0 to the length minus 1.
2.1) If the current value at the index is shorter than minLength set that as the new minLength, and set minIndex to the current index.
3) After the loop, minLength says how short the shortest was, and minIndex says where it was.

Simple, no?
 
Share this answer
 
Comments
ManojRGEC 14-May-17 6:01am    
Thanks for your solution :)

int minLength = int.MaxValue;
int index = -1;

for (int i = 0; i < test.Length; i++)
{
if (test[i].Length < minLength)
{
minLength = test[i].Length;
index = i;
}
}

If you are familiar with Linq, you could do this with one line of code.

C#
string[] test = { "absc", "abc", "abcder", "abcdg" };
var smallest = Array.IndexOf(test, test.First(s => s.Length == test.Min(st => st.Length)));

 
Share this answer
 
Comments
CHill60 14-May-17 4:33am    
If they can't work out how to traverse an array with a for loop something tells me they won't understand link :-)
ManojRGEC 14-May-17 5:41am    
Thanks, it is working for me. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900