从ListBox获取完整信息

时间:2017-10-24 12:27:21

标签: c# winforms listbox

我的主阵列看起来像这样:

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;
}

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

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

我想知道是否有消息,通过点击约翰我得到主阵列的所有其他信息(id,description,ountryofmanufacture)

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

1 个答案:

答案 0 :(得分:1)

如果您想查询集合,请尝试 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}\""); 
相关问题