2011-01-05 54 views
1

我有listview与combox =真正containg图像。每个项目都分配一个标签。 我可以得到聚焦项目的标签:获取ListView项目被检查

string name = this.lstview1.FocusedItem.Tag.ToString(); 

我可以检查项目的索引:

list = lstview1.CheckedIndices.Cast<int>().ToList(); 

我如何得到检查项目的标签?

回答

2

您可以使用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真的很有帮助。

+0

什么表示(i)i =>和(x)x => x.tag – Shahgee 2011-01-05 18:34:35

+0

是'IEnumerable .Select()'中使用的lambda表达式。它是'IEnumerable'的投影,其中的'Select()'被称为另一个'IEnumerable'。第一个基本上说:把'CheckedItems'的每个元素(称为x)和每个yield'x.Tag'。所以你会得到一个'IEnumerable ',它包含所有对应于'CheckedItems'的标签。 (希望清楚,英语不是我的第一语言...) – digEmAll 2011-01-05 18:40:55

+0

thanx,让我试试。 – Shahgee 2011-01-05 18:49:17

0

如何

 

var x = listView1.Items[listView1.CheckedIndices.Cast().ToList().First()].Tag; 
 

+0

Thanx for code.But我怎样才能为for循环制作索引。 AS首先总是表示序列的第一个元素。 – Shahgee 2011-01-05 18:47:39