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 s开发者_运维百科tore rest of elements in a different array.
Thanks, Ani
var orderedNames = names.OrderBy(name => name.Length);
string shortestName = orderedNames.First();
string[] otherNames = orderedNames.Skip(1).ToArray();
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});
There is no .Exclude
method (or extension method) for an Array and he didn’t say that he wanted to change the collection type for the new Array. Your use of the .Aggregate
is outstanding so let’s take it one step further and use .Aggregate
to do the excluding as well!
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 Hedlund’s technique is still far better because it’s easier to read! There are no bonus points for writing the most complicated answer... lol
精彩评论