如何使用LINQ在字符串[]中找到最长的字符串 [英] how to find the longest string in a string[] using LINQ

查看:245
本文介绍了如何使用LINQ在字符串[]中找到最长的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可变长度的字符串数组。目前我有一个循环遍历数组,找到数组中最长的字符串。有没有什么办法我可以使用LINQ以更高效和/或更清晰的方式写它?

I have an array of strings of variable length. Currently I have a loop that iterates through the array to find the longest string in array. Is there any way I could use LINQ to write it in more efficient and / or cleaner way?

推荐答案

更高效,但是做一些更干净的事情:

It won't be much more efficient, however it would be a bit cleaner to do something like:

var strings = new string[] { "1", "02", "003", "0004", "00005" };

string longest = strings.OrderByDescending( s => s.Length ).First();

输出:00005

这篇关于如何使用LINQ在字符串[]中找到最长的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆