Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C# LINQ expressions must end with Select or Group By Clause where as no such restriction in VB.Net

Tags:

c#

vb.net

linq

As my title is self explanatory, I know how to rectify it but why is it so in the first place?

Scenario

I wrote a VB.Net Code

Dim list As List(Of String) = New List(Of String)

//Code to populate list

Dim wherelinq As IEnumerable(Of String) = From s In list Where s.StartsWith("A")

This works fine and gives no error

but the same logic in C# fails

List<string> list = new List<string>();

//Code to populate list

IEnumerable<string> wherelinq = from s in list where s.StartsWith("A");

This gives error

enter image description here

Why this restriction in C#? Anything specific that I am missing?

like image 487
Nikhil Agrawal Avatar asked Oct 20 '12 12:10

Nikhil Agrawal


2 Answers

This is actually called a degenerate select. You don't need it when you use lambda syntax, which the query is compiled to. Why this restriction is required, I don't really know. These are probably some compiler related restrictions that really didn't have to be there.

like image 192
Jan W Avatar answered Oct 16 '22 08:10

Jan W


VB.NET and C# are different languages, so it is natural that the LINQ query syntax is different, too: C# requires select s, while VB.NET does not.

Microsoft's documentation requires that a query syntax query in C# must end in select or group:

A query expression must begin with a from clause and must end with a select or group clause. Between the first from clause and the last select or group clause, it can contain one or more of these optional clauses: where, orderby, join, let and even additional from clauses. You can also use the into keyword to enable the result of a join or group clause to serve as the source for additional query clauses in the same query expression.

See C# language specification, section 7.16, for details on the syntax.

var wherelinq = from s in list where s.StartsWith("A") select s;

You do not have to add select if you use the function syntax:

var wherelinq = list.Where(s => s.StartsWith("A"));
like image 5
Sergey Kalinichenko Avatar answered Oct 16 '22 10:10

Sergey Kalinichenko