以下代码旨在检查Excel单元格的值,并返回仅包含值为唯一的单元格的List(Of Excel.Range)
。带有问号的那条线是导致疼痛的那条线。
Private Function UniqueValues(ws As Excel.Worksheet) As List(Of Excel.Range)
Dim listRanges As New List(Of Excel.Range)
Dim dicValues As New Dictionary(Of Excel.Range, Object)
For Each rng As Excel.Range In ws.UsedRange
dicValues.Add(rng, rng.Value2)
Next
'Get list of cells with unique values
listRanges = dicValues.Keys.GroupBy(Function(x) x.Value2).ToList '????
dicValues = Nothing
Return listRanges
End Function
带有问号的行的正确代码是什么?请回复VB.NET,因为我很难将LINQ从C#转换为VB.NET,因为互联网上缺少VB.NET LINQ示例。
答案 0 :(得分:0)
应该做的伎俩:
listRanges = dicValues.Values.Distinct().ToList()
答案 1 :(得分:0)
这是我最终做的事情,这是有效的。我相信使用LINQ可能会更快,不需要第二个循环,所以如果有人有更优雅的解决方案,请发布。
Private Function UniqueValues(ws As Excel.Worksheet) As List(Of Excel.Range)
Dim listRanges As New List(Of Excel.Range)
Dim dicValues As New Dictionary(Of Excel.Range, Object)
For Each rng As Excel.Range In ws.UsedRange
dicValues.Add(rng, rng.Value2)
Next
'Get list of cells with unique values
Dim uniqueVals = dicValues.Where(Function(x)
Return dicValues.Where(Function(y) y.Value = x.Value).Count = 1
End Function)
For Each itm In uniqueVals
listRanges.Add(itm.Key)
Next
uniqueVals = Nothing
dicValues = Nothing
Return listRanges
End Function