LINQ query in .NET VISUAL STUDIO

5

I need to translate the following query from SQL to LINQ in .NET with C #:

This is the SQL query to translate:

SELECT COUNT(id_documento)
FROM documento

I need the value to be stored in a variable or to capture the number of records in a variable. Something similar to a structure like this:

var OrdersByCustomer = db.Salesorders.GroupBy(so => so.CustomerId)
                                     .Where(tos => tos.Count() > 5)
    
asked by jmtaborda 08.04.2018 в 06:09
source

3 answers

8

As follows to count the unique id_document values for the C # language:

Using LINQ:

var Consulta = (from x in db.Salesorders select id_documento).Distinct().Count();

Using Entity Framework:

var Consulta = db.Salesorders.GroupBy(x => x.id_documento)
                             .Select(x => x.First())
                             .ToList()
                             .Count;

As follows to count the unique id_document values for the VB language:

Using LINQ:

Dim NumElementosDistintos = (From x In db.Salesorders 
                            Select x.id_documento)
                            .Distinct()
                            .Count

With the following query you can count the amount of total id_document in the table for the C # language:

Using LINQ:

var Consulta = (from x in db.Salesorders select id_documento).Count()
  

or

var count = db.Salesorders.Count();

With the following query you can count the amount of total id_document in the table for the VB language:

Using LINQ:

Dim NumElementos = (From x In db.SalesOrder Select x.id_documento).Count
  

You can see examples of how to use them in the following links:

     

Examples of the LINQ query In Spanish

     

101 Examples of using LINQ: Count - Simple and Count - Conditional    In English

     

101 Examples of using LINQ: Select - Simple In English

     

Aggregation Operations (Visual Basic) In English

     

How to: Count, Sum, or Average Data by Using LINQ (Visual Basic) In   English

    
answered by 22.04.2018 в 20:23
4

Using lambda:

var count = db.documento.ToList().Count();

Using Linq:

var count = (from d in db.documento).Count();
  

I'm assuming you're using the entity framework in your project.

    
answered by 19.04.2018 в 22:30
2

You could do it this way a.

  

SELECT COUNT (document_id) FROM document

This query results in LINQ :

var consulta = from documento in db.Salesorders select id_documento;
var cantidad = consulta.Count();

Or you can do it from the following:

Dim consultaCount = Aggregate documento In db.Salesorders 
                          Into Count()

That is what happens to me based on your information. Greetings.

    
answered by 19.04.2018 в 21:07