【发布时间】:2013-11-20 16:18:46
【问题描述】:
我在 Visual Basic 中有一个数组,它需要返回最长的单词。如何在字符串数组中查找最长的单词?非常感谢任何帮助!
【问题讨论】:
我在 Visual Basic 中有一个数组,它需要返回最长的单词。如何在字符串数组中查找最长的单词?非常感谢任何帮助!
【问题讨论】:
一个 LINQ 替代方案是这样的:
Dim strings = New String() {"1", "02", "003", "0004", "00005"}
Dim longest As String = strings.OrderByDescending(Function(s) s.Length).FirstOrDefault()
【讨论】:
FirstOrDefault() 的唯一原因是null 字符串。
OrDefault 帐户为空,感谢您发现我的错字。我无法编辑评论,因为它发布时间太早了。
Dim longestWord = String.Empty
For Each word in strArray
If Not String.IsNullOrEmpty(word) AndAlso word.Length > longestWord.Length Then
longestWord = word
End If
Next
** 更新为空字符串 **
【讨论】:
类似这样的东西...(它是 c#,但应该很容易移植到 VB)
string[] stringArray = new string[] { "One", "Two", "Three", "Four" };
string longest = stringArray.OrderByDescending(x => x.Length).FirstOrDefault();
【讨论】:
如果我要在 C# 中使用 Linq 执行此操作,我会这样做:
var strings = new string[3] { "abc", "defg", "hijkl" };
string longest = strings.OrderByDescending(s => s.Length).FirstOrDefault();
【讨论】: