4
I have the following query LINQ which is in a method that returns all products:
var query = from p in Produtos
select new Produto
{
ProdutoId = p.ProdutoId,
Descricao = p.Descricao,
Preco = p.Preco,
Estoque = p.Estoque
};
return query;
I also have other methods that return the same fields being filtered by certain conditions ex:
var query = from p in Produtos
where p.Descricao.StartsWith(descricao)
select new Produto
{
ProdutoId = p.ProdutoId,
Descricao = p.Descricao,
Preco = p.Preco,
Estoque = p.Estoque
};
return query;
Is there any way to avoid repeating the passage:
select new Produto { ProdutoId = p.ProdutoId, Descricao = p.Descricao, Preco = p.Preco, Estoque = p.Estoque };
With this, if you want to add/remove some field, you wouldn’t have to change all methods.
Other solutions are also welcome.
Try to put inside a
switch statament
– StillBuggin
@Eduardoalmeida I was curious, please show how it is possible to resolve this with
switch
.– Maniero
I found this example in C#: http://stackoverflow.com/questions/17405348/avoiding-repeating-code-with-linq-query-optional-params I usually program in PHP (so I didn’t write in response), but the solutions can be approximated. What’s more, your solution looks more elegant.
– StillBuggin
@Eduardoalmeida actually in this example the
switch
is solving another problem, not the one presented here and it is questionable whether something would be cool to do in well modularized modern codes. The solution of the problem presented there is the same as here, but it was not theswitch
which made it possible. was the separation of what is a repetitive pattern from what varied.– Maniero
But that’s the idea. I say what I want and the
switch
tells how LINQ has to do. The parameters are sent to the query only if they meet a condition set inswitch
. If I pass this to the controller there is no problem, after all, the controller defines the behavior of my system through decision structures and theswitch
That’s what I’m talking about.– StillBuggin
Only have these fields in the table?
– Marco Souza
It’s just an illustrative example, it could have more fields. The purpose of the question is exactly to avoid code repetition problem if more fields need to be added. @GOKUSSJ4
– rubStackOverflow
@rubStackOverflow. See the example I answered.
– Marco Souza