【问题标题】:Get ListView items that are checked获取选中的 ListView 项
【发布时间】:2011-01-05 18:16:25
【问题描述】:

我有带有combox=true 包含图像的列表视图。每个项目都分配有一个标签。 我可以得到重点项目的标签:

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

我可以得到检查项目的索引:

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

如何获取被检查项目的标签?

【问题讨论】:

    标签: c# listview checkbox tags


    【解决方案1】:

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

    【讨论】:

    • 什么表示 (i) i=> 和 (x ) x=>x.tag
    • IEnumerable&lt;T&gt;.Select() 中使用的 lambda 表达式。这是IEnumerable 的投影,在其上称为Select() 到另一个IEnumerable。第一个基本上说:取CheckedItems 的每个元素(称为x)和每个yield x.Tag。所以你会得到一个IEnumerable&lt;object&gt;,其中包含与CheckedItems相对应的所有标签。 (希望清楚,英语不是我的第一语言......)
    • 最后加了一点解释 ;)
    【解决方案2】:

    怎么样

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

    ?

    【讨论】:

    • 感谢代码。但是如何为 for 循环创建索引。 AS first 总是表示序列的第一个元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    相关资源
    最近更新 更多