1

我正在尝试根据组合框项目中的最大字符串来更改组合框的 DropDownWidth 。下面的代码返回所有项目的最大字符串长度。

 Dim maxStringLength As Integer = cboDt.AsEnumerable().
                  SelectMany(Function(row) row.ItemArray.OfType(Of String)()).
                  Max(Function(str) str.Length)

cboDt 是附加到组合框的数据表。
我想返回实际的字符串。例如,如果组合框项目是:
“aaa”
“bbbb”
“ccccc”
我的代码返回maxStringLength = 5(因为5是所有项目的最大字符数-这里是ccccc)我希望代码重新调整“ccccc”(当然在字符串变量中)

4

3 回答 3

3

按字符串长度降序排列列表,然后取第一个结果。

Dim maxStringLength As Integer = 
    cboDt.AsEnumerable().
    SelectMany(Function(row) row.ItemArray.OfType(Of String)()).
    OrderByDescending(Function(str) str.Length).
    First()  ' You can use FirstOrDefault here, if you are
             ' not certain there will be a result.
于 2013-01-31T12:57:02.273 回答
2

假设 的第一列DataTable显示在ComboBox

Dim maxStringLength As Integer = cboDt.AsEnumerable().
        Max(Function(r) r.Field(Of String)(0).Length)

请注意,这假定这要求此列是 never null

(我看不出你为什么要测量表的(可能可用的)其他列的长度,因为它们根本没有显示ComboBox。)

更新

在 Combobox 中查找最大字符串

现在我明白了,你想要的是字符串而不是长度:

Dim longestString = cboDt.AsEnumerable().
        OrderByDescending(Function(r) r.Field(Of String)(0).Length).
        First().Field(Of String)(0)
于 2013-01-31T13:07:34.247 回答
0

您可以使用 linq 和 Find the Index ofmaxStringLength = 5

Dim ls = comboBox4.Items.Cast(Of String)().ToList()
Dim index = ls.FindIndex(Function(c) c.ToString().Count() >= 5)
comboBox4.SelectedIndex = index

或使用Max() 方法

Dim ls = comboBox4.Items.Cast(Of String)().ToList()
Dim index = ls.Max()
comboBox4.Text = index
于 2013-01-31T13:08:34.987 回答