Understand that LINQ is a single language. There are two forms and syntax but in essence they perform the same. The most declarative syntax is syntactic sugar on top of existing methods. So what you do in declarative form can do in method form (roughly).
The select
used in the question is, in the background, the method Select()
LINQ. The compiler transforms one way of writing into the other more "normal" in the C#language. So the only difference you will find is the form of the same call. It would be something like this:
.Select(s => new { Codigo = s.id_sub_categoria,
SubCategoria = s.descricao,
CodigoCategoria = s.CategoriaProduto.id_categoria,
Categoria = s.CategoriaProduto.descricao})
What is being used in an auxiliary way in the two forms is the anonymous type. In it you create a class on-the-fly specifying the properties that should be available in it. And it will already start by typing the value right there. It will be filled with each item.
The name is very suggestive for those who are used to SQL. This is the way to select which fields you want. Can use any valid expressions in the language.
We usually use new
to create a new instance of a type and then put the name of the type and optionally initialize your values, right? Something like that:
var x = new Tipo { Prop1 = 1, Prop2 = "teste" }; //esta estrutura está definida em Tipo
Well, as an anonymous guy has no name and properties can be set on time.
var x = new { Prop1 = 1, Prop2 = "teste" }; //esta estrutura está sendo "inventada" agora
Remembering that in a lambda we don’t need to write the return
, but if we wanted to, we would do so:
.Select(s => return new { Codigo = s.id_sub_categoria,
SubCategoria = s.descricao,
CodigoCategoria = s.CategoriaProduto.id_categoria,
Categoria = s.CategoriaProduto.descricao})
Just to show what each thing is, let’s say you want to hypothetically (because it makes little sense) return a constant value:
.Select(s => 1)
Here I did not use the anonymous type, only the method and I passed to him a lambda very simple. In the declarative form this would be the same as:
select 1
I put in the Github for future reference.
Another example would be a Select(item => item)
which is the equivalent of a SELECT *
SQL. But of course this method is totally expendable. If it is not present, it is exactly what will be selected.
The where
is like that. The join
too. It’s all like that. The list is immense. Yet not everything has a one-to-one relationship.
That right there is expression lambda. I mean with method syntax?
– Maniero
@bigown Yes that’s right, method syntax, for example
db.Categoria.First()
this way or another if there is.– gato