【问题标题】:Get the full info from the ListBox从 ListBox 获取完整信息
【发布时间】:2017-10-24 12:27:20
【问题描述】:

我的主数组如下所示:

String[] main = new String[products.Count];

for (int i = 0; i < main.Length; i++)
{
    main[i] = products[i].id + 
              products[i].productowner + 
              products[i].description + 
              products[i].countryofmanufacture;
}

还有一个只有少数 products[i].productowner 值的字符串列表:

List<string> specificproductowners  = new List<string>();

我想知道通过单击 John 是否可以从主数组中获取所有其他信息(id、描述、ountryofmanufacture)

         A Windows Form listBox (specificproductowners)
         -----------------------------
         |        John               |            
         |        Alex               |
         |        Tom                |
         |        Jan                |
         -----------------------------

【问题讨论】:

    标签: c# winforms listbox


    【解决方案1】:

    当你想要查询 collection 时,试试 Linq,像这样:

    List<string> specificproductowners = products
      .Select(product => product.productowner)
      .Distinct()
      // .OrderBy(owner => owner) // Uncomment, if you want to sort 
      .ToList();  
    

    如果您想将所有者添加到 ListBox

    MyListBox.Items.AddRange(products
      .Select(product => product.productowner)
      .Distinct()
      // .OrderBy(owner => owner) // Uncomment, if you want to sort
      .ToArray());             // AddRange wants an array
    

    编辑:如果你想获得products中被productowner过滤的所有项目,你可以使用另一个Linq

    string owner = "Alex";
    
    List<string> filtered = products
      .Where(product => product.productowner == owner) // "Alex" only
      .Select(product => string.Join(", ",  // let's combine into "id, description, country"
         product.id, 
         product.description,
         product.countryofmanufacture))
      .ToList();
    
     ...
     MessageBox.Show(
         string.Join(Environment.NewLine, filtered), 
       $"Test filtered for product owner \"{owner}\""); 
    

    【讨论】:

    • 比我的方法好得多,但我的意思是我已经在 ListBox 中拥有所有者,如果双击名称,我想获取每个所有者的完整信息
    • @Simle: 那么产品负责人(比如,Alex)你想获得products 中所有具有productowner == "Alex" 的项目?
    • 是的,通过在 alex 上双击(或移动鼠标)我得到一种包含所有 alex 信息的临时 MessageBox
    • @Simle:在这种情况下,您似乎只想过滤掉 products - 另一个 Linq (Where)
    • 我的主要问题是单击列表框中的项目,因为我知道如何获取单击项目的索引,但不知道它的值,我找不到这样做的方法。跨度>
    猜你喜欢
    • 1970-01-01
    • 2019-11-15
    • 2020-10-10
    • 2016-06-13
    • 2023-03-11
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多