2

How can we transform a list of string or a list of object to a ListViewItemCollection in one line with linq, where object is for example a person with Name property that will be displayed to the ListViewItem.

Here is my current code :

foreach (string word in sf.lstWords)
{
  lvWords.Items.Add(new ListViewItem(word));
}

Use ListView.ListViewItemCollection.AddRange and the Linq method Select

lvWords.Items.AddRange(sf.lstWords.Select(t => new ListViewItem(t)).ToArray());

I use ToArray() because the signature of AddRange is void AddRange(ListViewItem[])

4

1 回答 1

11

使用ListView.ListViewItemCollection.AddRange和Linq方法Select

lvWords.Items.AddRange(sf.lstWords.Select(t => new ListViewItem(t)).ToArray());

我使用ToArray()是因为 AddRange 的签名是无效的AddRange(ListViewItem[])

于 2013-02-03T19:33:42.787 回答