tags:

views:

123

answers:

2

I have a Array

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

Is there any way to find which is the shortest(Length wise) element in this array and then store rest of elements in a different array.

Thanks, Ani

+1  A: 

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 other array

var otherArrays = names.Exclude(new List<string>(){shortestName});
Ngu Soon Hui
+1. I love how C# made such a thing so simple ;) However you're missing the second part of the question which demands to store the others elements in an array.
ereOn
that gives you the length of the shortest item, tho; it doesn't tell you which item that is
David Hedlund
Thanks a lot, I am new never tried this code..I ll try...Thanks again
Ani
@Ani, code updated to fix a bug.
Ngu Soon Hui
@Ngu Thanks a lot.
Ani
+6  A: 
var orderedNames = names.OrderBy(name => name.Length);

string shortestName = orderedNames.First();

string[] otherNames = orderedNames.Skip(1).ToArray();
David Hedlund
Thanks a lot..This worked...ur help appreciated...
Ani
Note that this will be inefficient for large arrays; sorting the array requires O(n lg n) comparisons. There is an algorithm to solve this problem that is O(n). I also note that you sort the list *twice* in your solution. Calling First() orders the list. Calling Skip *sorts the original list again*. Remember, LINQ doesn't know that you haven't changed "names" on another thread between the calls; the answer might be different so the result has to be recomputed.
Eric Lippert
@Eric Lippert: ah yes, good point. adding `.ToList()` in the original assignment to `orderedNames` should remedy that last issue, right?
David Hedlund
Yes, though then you have the problem that you are *copying* the same data twice; once to a list that is only useful for its first element, and then to the shorter array.
Eric Lippert