【发布时间】:2014-02-18 01:54:07
【问题描述】:
我想根据子项索引从 ListViewItemCollection 中删除重复项。
使用LINQ 的方法很重要。
这是我没有运气的尝试:
Private Function RemoveListViewDuplicates(ByVal Items As ListView.ListViewItemCollection,
ByVal CompareColumn As Integer) As ListView.ListViewItemCollection
Dim Deduplicated =
(From Item As ListViewItem In Items
Group By Item.SubItems(CompareColumn).Text Into Distinct()) '.ToArray
' At this point the good thing is that the '.Distinct' grouped member of the
' resulting 'Deduplicated' object contains only the non-duplicated ListviewItems
' but, I can't find the way to return that single member '.Distinct' as a 'ListView.ListViewItemCollection'
' instead of returning both '.Text' and '.Distinct' members.
'
' I just want to return the 'Items' object that I pass to the function but without duplicates,
' and in the same return-type of the object that I've passed to this function
' (ListView.ListViewItemCollection) as you can understand.
Return Deduplicated
End Function
然后我应该可以这样做:
Dim items As ListView.ListViewItemCollection =
RemoveListViewDuplicates(ListView1.Items, 0)
For Each Item As ListViewItem In items
MsgBox(Item.Text)
Next Item
更新
我正在尝试回答here 的解决方案,但稍作修改以保留集合中的 1 个重复项,我遇到的问题是这直接在 ListView 控件上工作,这不是我想要的,我想要处理存储列表视图控件的当前项但在删除重复项时不直接影响控件的对象...
这是方法:
Private Function RemoveListViewDuplicates(ByVal Items As ListView.ListViewItemCollection,
ByVal SubitemCompare As Integer) As ListView.ListViewItemCollection
Dim Duplicates As ListViewItem() =
Items.Cast(Of ListViewItem)().
GroupBy(Function(Item As ListViewItem) Item.SubItems(SubitemCompare).Text).
Where(Function(g As IGrouping(Of String, ListViewItem)) g.Count <> 1).
SelectMany(Function(g As IGrouping(Of String, ListViewItem)) g).
Skip(1).
ToArray()
' This removes the items from the listview control, directlly
For Each Item As ListViewItem In Duplicates
Items.Remove(Item)
Next Item
Return Items
End Function
所需用途:
Dim DuplicatedItems As ListView.ListViewItemCollection =
New ListView.ListViewItemCollection(ListView1)
Dim DeDuplicatedItems As ListView.ListViewItemCollection =
RemoveListViewDuplicates(DuplicatedItems, 0)
' I add the Items without duplicates on another Listview,
' preserving the duplicates on the original Listview1 control.
ListView2.Items.AddRange(DeDuplicatedItems)
【问题讨论】:
-
你见过吗:stackoverflow.com/q/3603036/1070452 我要提到一个在那里使用的比较器。另外,我很好奇为什么使用 LINQ 很“重要”。
-
@Plutonix 是的,我在创建问题之前已经看过它,但老实说,我没有阅读答案末尾有趣的部分。我正在尝试使用该解决方案,但给了我一个小问题,也许很容易为你解决,如果你能阅读我更新的问题,请。 PS:我喜欢 LINQ 语法,因为它简化了分句,我知道 For 循环更有效,但我想以多种方式替换 For 的用法。
标签: .net vb.net linq visual-studio listview