【问题标题】:Find the maximum string in Combobox在 Combobox 中查找最大字符串
【发布时间】:2013-01-31 12:52:34
【问题描述】:

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

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

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

【问题讨论】:

  • 您的DataTable 有多少列,您在ComboBox 中使用了哪些列?其余的与您的maxStringLength 无关。
  • 只是为了回答这个问题。我的数据表总是有两个(显示和值列)

标签: vb.net visual-studio-2010


【解决方案1】:

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

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.

【讨论】:

  • 错误 1 ​​'OrderByDesc' 不是 'System.Collections.Generic.IEnumerable(Of String)' 的成员。
  • 我找到了:OrderByDescending
【解决方案2】:

假设DataTable的第一列显示在ComboBox中:

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

请注意,这假定这要求此列永远不是null

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

更新

在 Combobox 中查找最大字符串

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

Dim longestString = cboDt.AsEnumerable().
        OrderByDescending(Function(r) r.Field(Of String)(0).Length).
        First().Field(Of String)(0)

【讨论】:

  • 原因是字符串的长度,他想修改长度DropDownWidth的基数:)
  • 先生,我猜 OP 只使用一列 ComboBox and DataTable
  • @spajce:编辑了我的答案。
  • @TimSchmelter:您的代码返回 .Length,但我想要字符串。您对列的注释是正确的
  • @Nianios,蒂姆先生的回答已经更新了。为你+1先生..你的头脑很好:)
【解决方案3】:

您可以使用 linq 和查找 maxStringLength = 5 的索引来实现此目的

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

或使用Max() Method

Dim ls = comboBox4.Items.Cast(Of String)().ToList()
Dim index = ls.Max()
comboBox4.Text = index

【讨论】:

  • 我喜欢你的想法,不幸的是我的 Combobox 是第三方,它没有 .Items
  • ..怎么样?你能说出你的 comboBox 第三方吗?
  • 抱歉,我的组合框不是来自 Visual Studio 的组件。不便之处,敬请见谅
  • 我不相信你的第三方组合框没有..或类似ObjectionCollection的东西,但没关系:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多