【问题标题】:Is it possible to do a ListViewItem array?是否可以做一个 ListViewItem 数组?
【发布时间】:2016-07-21 11:17:45
【问题描述】:

是否可以声明一个ListViewItem数组?例如

ListViewItem[] arrayItems;
  • 如果是可能,我该如何填充数组?

  • 是否有可能有不是固定大小的数组

【问题讨论】:

  • 您可以拥有任何类型的数组并内联或使用循环对其进行初始化。或者使用listView1.Items.Cast<ListViewItem>().ToArray() 获取数组中的列表视图项。你真正的问题是什么?

标签: c# arrays winforms listview


【解决方案1】:

是的!可以将 List 声明为数组。

对于指定长度,请在下面使用:

ListViewItem[] arrayItems = new ListViewItem[5];

arrayItems[0] = new ListViewItem("Text1");
arrayItems[1] = new ListViewItem("Text2");
// so on

对于未指定的长度,请在下面使用:

List<ListViewItem> arrayItems = new List<ListViewItem>();

arrayItems.Add(new ListViewItem("Text1"));
arrayItems.Add(new ListViewItem("Text2"));

// When you want to pass it as array, use arrayItems.ToArray();

或者如果你有一些带有一些文本属性的对象列表:

List<ListViewItem> arrayItems = dataSourceObject.Select(x => new 
                                                  ListViewItem(x.TextProperty)).ToList();

【讨论】:

  • 但在那种情况下,我需要指定许多我想要的项目,我想继续在循环中添加它们,但没有长度限制我
【解决方案2】:

您似乎在寻找List&lt;ListViewItem&gt;,而不是数组(ListViewItem[]):

List<ListViewItem> myItems = new List<ListViewItem>();

// Just add items when required; 
// have a look at Remove, RemoveAt, Clear as well
myItems.Add(new ListViewItem("Text 1"));

// When you want read/write the item do as if you have an array
ListViewItem myItem = myItems[0]; 

您可以使用 Linq 从现有的ListView 获取项目:

myItems = listView1.Items
  .OfType<ListViewItem>()
  .ToList();

或追加现有列表:

List<ListViewItem> myItems = new List<ListViewItem>();
...
myItems.AddRange(listView1.Items.OfType<ListViewItem>());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2011-07-09
    • 2013-04-18
    相关资源
    最近更新 更多