问题
Again, just out of curiosity:
After I have programmed several projects in VB.Net I to my surprise discovered that there are some more than subtle differences between C# and VB.NET LINQ usage. For example, if we want to group elements by multiple properties (columns) we need to create a new anonymous type explicitly:
var procs = from c in Process.GetProcesses()
group c by new {c.BasePriority, c.Id} into d
select d;
whereas in VB.NET more straightforward syntax will already do:
Dim b = From c In Process.GetProcesses()
Group c By c.BasePriority, c.Id Into Group
Select Group
So, one does not need to create a type with "new" here.
What are the other differences? Is there any good comparison between the LINQ syntax in C# and VB.NET?
回答1:
There are some differences that I know of, mostly that VB.NET's LINQ has some hidden gems:
- Not explicitly LINQ related, but VB.NET supports the
Key
modifier on anonymous types. This allows you to define which properties in the anonymous type are used when comparing anonymous types. As far as I can tell with C#; it uses everything. This is where VB.NET has an actual advantage. - VB.NET supports the
Skip
operation as a keyword:Dim returnCustomers = From a In list Skip numToSkip Select a
You can do this in C#; but it has to be through the extension method, there is no syntactic sugar. - VB.NET LINQ also supports
Skip While
:From a In list Skip While someCondition Select a
Again, C# can do this; but only through the extension method. - and 4.5.: The same as 2 & 3 except with
Take
andTake While
- The
Select
keyword is optional in VB.NET. If you want to select what is current; then that works fine:Dim shortWords = From l In list Where l.Length < 10
in C#; the Select part is required:var shortWords = from l in list where l.Length < 10 select l
Those are the additional "features" of VB.NET's LINQ that I am aware of.
For example; with C#:
var skip10 = (from c in customers select c).Skip(10);
And in VB.NET
Dim skip10 = From c In Customers Skip 10
You can see the documentation for all of these here: http://msdn.microsoft.com/en-us/library/ksh7h19t(v=VS.90).aspx
回答2:
Try to look at this:
Visual Basic vs C# LINQ syntax
regards
来源:https://stackoverflow.com/questions/6515037/differences-in-linq-syntax-between-vb-net-and-c-sharp