How to convert a list<string> or list<object> to a ListView.ListViewItemCollection in one line

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

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

回答1:

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[])



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!