In the case of var consulta = from x in bd.Tabla select x;
the equivalent in the methods syntax would be
var consulta = bd.Tabla.Select(x => x);
However the .Select(x => x)
is most of the cases redundant since it returns the same elements without any modification for what you could do simply:
var consulta = bd.Tabla;
The only difference between the latter and the one above is the type of data it returns.
The first returns an IQueryable while the latter returns the data type of bd.Table (in case of Entity Framework for example DbSet<T>
)
The reason why these two syntax exist is simple.
When the C # team made C # 3.0 together with NET Framework 3.0 they added many new things to the language including: lambdas, type inference (var), extension methods and partial methods, with the aim of being able to implement LINQ and its Querys syntax. The primary objective was to convert the imperative style in which the queries, selections, projections and other operations of the relational algebra were made to a declarative style as close to SQL as possible. p>
So given a variable
IEnumerable<Personas> personas = ....;
A code similar to this
IEnumerable<PersonasResumen> mayoresDeEdad = new List<Persona>();
foreach(Persona p in personas)
{
if(p.Edad >= 18)
{
mayoresDeEdad.Add(p);
}
}
It became simply
var mayoresDeEdad = from p in personas
where p.Edad >= 18
select p;
The thing becomes even more complicated if we take into account operations like JOIN
The syntax of methods is only the penultimate step to get to that syntax and sometimes it is preferred because in some cases it is shorter for example in the case that it is not required to make a projection (select only certain fields) the above may have been written in this way.
var mayoresDeEdad = personas.Where(p => p.Edad >= 18);
The select is not necessary in this case, in the query syntax it is mandatory.
For me the best explanation of LINQ is in this prehistoric interview of 2005 by the same teacher Anders Hejlsberg, creator of C #, LINQ and TypeScript. The video lasts 37 minutes, has low quality and is filmed with a camera pointing to the screen but the content and explanation are pure gold.
Anders Hejlsberg LINQ Demo 2005
Or if you want a better quality and you have a little more time this other video of the Lang.NET 2006 Compiler Symposium is also an excellent alternative
Anders Hejlsberg LINQ
Finally I just remind you that Insert, Update or Delete are not part of LINQ since as its name implies: Language Integrated Query is just a query language, not operations with side effects about the data.
It also works on any IEnumerable<T>
not only on databases, so the way to do INSERT
, UPDATE
or DELETE
depends on the provider that is being used, for example in the Entity Framework:
INSERT
db.Personas.Add(persona);
db.SaveChanges();
UPDATE
persona.Nombre = nuevoNombre;
db.SaveChanges();
DELETE
db.Personas.Remove(persona);
db.SaveChanges();