【发布时间】:2011-01-05 18:16:25
【问题描述】:
我有带有combox=true 包含图像的列表视图。每个项目都分配有一个标签。 我可以得到重点项目的标签:
string name = this.lstview1.FocusedItem.Tag.ToString();
我可以得到检查项目的索引:
list = lstview1.CheckedIndices.Cast<int>().ToList();
如何获取被检查项目的标签?
【问题讨论】:
我有带有combox=true 包含图像的列表视图。每个项目都分配有一个标签。 我可以得到重点项目的标签:
string name = this.lstview1.FocusedItem.Tag.ToString();
我可以得到检查项目的索引:
list = lstview1.CheckedIndices.Cast<int>().ToList();
如何获取被检查项目的标签?
【问题讨论】:
您可以使用CheckedItems 属性代替CheckedIndices:
var selectedTags = this.listView1.CheckedItems
.Cast<ListViewItem>()
.Select(x => x.Tag);
反正CheckedIndices也可以用,例如:
var selectedTags = this.listView1.CheckedIndices
.Cast<int>()
.Select(i => this.listView1.Items[i].Tag);
编辑:
LINQ小解Select():
以下代码:
var selectedTags = this.listView1.CheckedItems
.Cast<ListViewItem>()
.Select(x => x.Tag);
foreach(var tag in selectedTags)
{
// do some operation using tag
}
在功能上等于:
foreach(ListViewItem item in this.listView1.CheckedItems)
{
var tag = item.Tag;
// do some operation using tag
}
在这个特定的示例中,它的用处不大,代码长度也不短,但是,相信我,在许多情况下,LINQ 真的很有帮助。
【讨论】:
IEnumerable<T>.Select() 中使用的 lambda 表达式。这是IEnumerable 的投影,在其上称为Select() 到另一个IEnumerable。第一个基本上说:取CheckedItems 的每个元素(称为x)和每个yield x.Tag。所以你会得到一个IEnumerable<object>,其中包含与CheckedItems相对应的所有标签。 (希望清楚,英语不是我的第一语言......)
怎么样
var x = listView1.Items[listView1.CheckedIndices.Cast().ToList().First()].Tag;
?
【讨论】: