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
Why this restriction in C#? Anything specific that I am missing?
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.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With