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 a syntactic sugar over existing methods. So what you do in declarative form can do in method form.
The wc% used in the question is basically the select
"of LINQ. The compiler transforms a way of writing in the other more "normal" in C # language. So the only difference you'll find is the form of the call itself. It would look 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 as an aid in both forms is anonymous type . In it you create an on-the-fly class specifying the properties that should be available in it. And you are initializing the value right there. It will be populated with each item.
The name is very suggestive for those who are accustomed to SQL. This is how to select which fields you want. You can use any valid expressions in the language.
Normally we use Select()
to create a new instance of a type and then we put the type name and optionally we initialize its values , right? Something like this:
var x = new Tipo { Prop1 = 1, Prop2 = "teste" }; //esta estrutura está definida em Tipo
Well, with an anonymous type it does not have a name and properties can be defined on the fly.
var x = new { Prop1 = 1, Prop2 = "teste" }; //esta estrutura está sendo "inventada" agora
Remembering that in a lambda we do not need to type new
, but if we wanted, we would do this:
.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) to return a constant value:
.Select(s => 1)
Here I did not use the anonymous type, just the method and I gave him a very simple lambda . In declarative form this would be the same as:
select 1
Another example would be a return
that is equivalent to a Select(item => item)
of SQL. But of course this method is totally dispensable. If it is not present, it is exactly what will be selected.
The SELECT *
is like this. The where
also. It's all like that. The list is huge . However not everything is a one-to-one relationship.