How to select fields in a lambda expression query?

Asked

Viewed 1,543 times

6

Through the select new from LINQ I can select which fields will be displayed in the query, for example:

var subCategorias = from s in db.SubCategoria
                    join c in db.CategoriaProduto 
                        on s.id_categoria equals c.id_categoria
                    where s.descricao.Contains(descricao)
                    select new
                    {
                        Codigo = s.id_sub_categoria,
                        SubCategoria = s.descricao,
                        CodigoCategoria = s.CategoriaProduto.id_categoria,
                        Categoria = s.CategoriaProduto.descricao          
                    };

In the example above the fields that will be available after the query is mounted by the method ToList() will be the following fields:

Code (id_sub_category)
Subcategory (description of)
Code category (id_category)
Category (description)

However, I would like to know how I can select the fields I want in a query made in lambda expression or if there is any resource similar to the select new in lambda expression?

  • That right there is expression lambda. I mean with method syntax?

  • @bigown Yes that’s right, method syntax, for example db.Categoria.First() this way or another if there is.

2 answers

5


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.

  • And if I wanted to select all fields with the method Select(x =>...), similar to the select * of SQL?

  • 1

    @cuttlefish .Select(item => item);

  • 1

    @drmcarvalho is what jbueno said. Of course these things do not make as much sense to use in a select, at least not under normal conditions. There may even be some situation, but I think it would be more something conditional. This Select equivalent to * is the same as not having the method, unlike SQL where it is required, is the basis of the command, the default of LINQ is a select * so to speak. In the declarative LINQ from is the basis of the command. In the imperative not even this is really necessary, until a Select() alone serves, or a Where(), the most common.

3

In good looking, observe:

.Select(s => new {

});

Complete:

var subCategorias = db.SubCategoria
            .Join(db.CategoriaProduto, c => c.id_categoria, 
                                       a => a.id_categoria, (c,a) => new {c,a})
            .Where(w => w.c.descricao.Contatins(descricao))
            .Select(s => new {
                    Codigo = w.c.id_sub_categoria,
                    SubCategoria = w.c.descricao,
                    CodigoCategoria = w.c.CategoriaProduto.id_categoria,
                    Categoria = w.c.CategoriaProduto.descricao  
            }).ToList();

Explanation: What are lambda expressions?

  • In this case I carry the fields inside the keys { } ?

  • 1

    Now I get it.

  • That, inside the key!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.