您可以使用一個ListViewItem構造函數接受數組串(其中第一後元素是子項)
假設你的類有屬性LastName
和Name
ListView.Items.AddRange(ListData.Where(i =>
string.IsNullOrEmpty(searchBox.Text)
|| i.ID.StartsWith(searchBox.Text))
.Select(c => new ListViewItem // this part
(
new string[]{c.ID, c.Name, c.LastName}
)).ToArray());
如果單一的ListViewItem的創建變得更加複雜,可以考慮使用一個函數,:
ListView.Items.AddRange(ListData.Where(i =>
string.IsNullOrEmpty(searchBox.Text)
|| i.ID.StartsWith(searchBox.Text))
.Select(c => CreateListViewItemFromElement(c)).ToArray());
private ListViewItem CreateListViewItemFromElement(MyClass element)
{
// handle the element to create a "complete" ListViewItem with subitems
ListViewItem item = new ListViewItem(c.ID);
....
return item;
}
(實際上,我會用後者在任何情況下,它更可讀我)
刪除從現場開始一段時間的LINQ,然後回答自己「我應該怎麼做才能將ListViewItem添加到我的ListView中,同時填充Column name和LastName?」 –
那麼,第一列是一個項目,下一列是從這個項目的子項目。 – yerpy