Find the shortest element in an array

I have an array

string[] names = { "Jim Rand", "Barry Williams", "Nicole Dyne", "Peter Levitt", "Jane Jones", "Cathy Hortings"};

      

Is it possible to find the shortest (length wise) element in this array and then store the rest of the elements in another array.

Thanks, Ani

+2


a source to share


3 answers


var orderedNames = names.OrderBy(name => name.Length);

string shortestName = orderedNames.First();

string[] otherNames = orderedNames.Skip(1).ToArray();

      



+9


a source


In C #,. Net 3.5:

string shortestName = names.Aggregate((n1, n2)=>n1.Length<n2.Length?n1:n2);

      



This is how you can store other elements in another array

var otherArrays = names.Exclude(new List<string>(){shortestName});

      

+2


a source


There is no method .Exclude

(or extension method) for the array, nor did he say he wants to change the collection type for the new array. Your usage is .Aggregate

outstanding, so let's take it one step further and use .Aggregate

it to make an exception!

Like this:

string shortestName = names.Aggregate((n1, n2) => n1.Length < n2.Length ? n1 : n2);
string nonArrayString = names.Aggregate((n1, n2) => n2 != shortestName ? n1 + " " + n2 : n1);
string[] newNames = nonArrayString.Split(' ');

      

David Hedlunds' technique is still much better because it is easier to read! There are no bonus points for writing the hardest answer ... lol

+1


a source







All Articles