Linq discrepancy between C# and VB.Net

  • Thread starter Thread starter Chris Dunaway
  • Start date Start date
C

Chris Dunaway

I use the following the C# Linq expression to find a list of processes
with unique names and it returned the results I
expected. However, curiously, the VB version did not seem to work.
Can anyone correct my VB version so that it returns the same results
as the C# version?

C# version works (new keyword used so data binding will work
correctly):

var uniqueProcs = Process.GetProcesses()
.OrderBy(p => p.ProcessName)
.Select(p => new { p.ProcessName })
.Distinct();

VB version doesn't work (New keyword used so data binding will work
correctly):

Dim uniqueProcs = Process.GetProcesses() _
.OrderBy(Function(p) p.ProcessName) _
.Select(Function(p) New With {p.ProcessName}) _
.Distinct()

When I say that the VB version doesn't work, I mean that it returns a
list, but the duplicates are not removed.

Thanks,

Chris
 
In VB you have to use the "key" keyword (don't ask me why ?) :

Dim uniqueProcs = Process.GetProcesses() _
.OrderBy(Function(p) p.ProcessName) _
.Select(Function(p) New With {KEY p.ProcessName}) _
.Distinct()

My personal preference would be to use :

Dim uniqueprocs = From p In Process.GetProcesses _
Order By p.ProcessName _
Select p.ProcessName Distinct
 
In VB you have to use the "key" keyword (don't ask me why ?) :

Dim uniqueProcs = Process.GetProcesses() _
.OrderBy(Function(p) p.ProcessName) _
.Select(Function(p) New With {KEY p.ProcessName}) _
.Distinct()

My personal preference would be to use :

Dim uniqueprocs = From p In Process.GetProcesses _
Order By p.ProcessName _
Select p.ProcessName Distinct

--

Yes, so would, but the question originally arose from how to databind
the result to a DataGridView. The query you show won't display
properly in a DataGridView. Instead it has to be changed as so:

Dim uniqueprocs = From p In Process.GetProcesses _
Order By p.ProcessName _
Select New With {Key p.ProcessName}
Distinct

Thanks for the response and the solution.

Chris
 
Chris Dunaway said:
Yes, so would, but the question originally arose from how to databind
the result to a DataGridView. The query you show won't display
properly in a DataGridView. Instead it has to be changed as so:

Dim uniqueprocs = From p In Process.GetProcesses _
Order By p.ProcessName _
Select New With {Key p.ProcessName}
Distinct

Thanks for the response and the solution.

Chris

Paul Vick has an explanation here for the difference in behaviour: -
http://www.panopticoncentral.net/archive/2007/05/11/20566.aspx

Nick Hall
 
Back
Top