hey guys, i have an array which contains some elements, now i want to check which is the largest element in the array, so what could be the query in Linq...
Please reply as soon as p开发者_运维百科ossible.
string[] myArray = { "a", "b", "four" };
string longest = myArray.OrderByDescending(s => s.Length).FirstOrDefault();
...and "longest" will be equal to "four".
First, use OrderByDescending to sort the array. The result is an IEnumerable of the original strings but in the correct order (in this case descending by length). Then, using the now order IEnumerable (really an IOrderedEnumerable), take the first item - which is the longest.
Note: I use "FirstOrDefault" as good practice. You could have just used "First" here. If you are unsure whether or not your result will be null, you should use FirstOrDefault which will return the first element if it exists, otherwise it will return the default value of that Type. For a string it would return null, for a bool it would return false, for an int it would return 0, etc. In this case it is 100% safe to just use "First" instead since you know your string array is not null.
Alternatively, you can just use Max if you are lazy like me and prefer to keep typing to a minimum. :)
string longest = myArray.Max();
精彩评论