Grouping query by date

1

I am developing a query with C #, but I have a problem to accomplish the same. I need to group by date.

Code:

public void BuscarVendaDeProdurtos_Saidas()
{
    var data1 = Convert.ToDateTime(dateINI_Saida.Text);
    var data2 = Convert.ToDateTime(dateFINI_Saida.Text);
    var cod = Convert.ToInt64(textBox8.Text);

    var pesquisa = from p in dc.ITEMVENDA
    orderby p.CD_PRODUTO descending
    where p.CD_PRODUTO == cod && p.Data_Venda >= data1 && p.Data_Venda <= data2
    select new
    {

        p.NM_PROD,
        p.Data_Venda,
        p.QT_PRODV,
    };

    dataGridView2.DataSource = pesquisa.ToList();

    Soma = 0;
    foreach (DataGridViewRow dr in dataGridView2.Rows)
    Soma += Convert.ToDecimal(dr.Cells[2].Value);
    textBox12.Text = Convert.ToString(string.Format("{0:n}", Soma));
}

This search returns this:

Data Produto      Qt
20/10/2017……………….  3
20/10/2017 …………….. 1

I need something like this:

Data Produto     Qt
20/10/2017………………. 4

A single date with its sums added up.

    
asked by anonymous 24.10.2017 / 12:21

2 answers

0

Try to group by a date formatted with dd / mm / yyyy

public void BuscarVendaDeProdurtos_Saidas()
{
    var data1 = Convert.ToDateTime(dateINI_Saida.Text);
    var data2 = Convert.ToDateTime(dateFINI_Saida.Text);
    var cod = Convert.ToInt64(textBox8.Text);

    var pesquisa = from p in dc.ITEMVENDA
    orderby p.CD_PRODUTO descending
    where p.CD_PRODUTO == cod && p.Data_Venda >= data1 && p.Data_Venda <= data2
    select new
    {

        p.NM_PROD,
        p.Data_Venda,
        p.QT_PRODV,
    };

    dataGridView2.DataSource = pesquisa // .ToList() 
    //.OrderBy(x => DateTime.ParseExact(x.Data_Venda, "dd/MM/yyyy", null))
        .OrderBy(x => x.Data_Venda.ToString("dd/mm/yyyy"))
        .ToList();
    ;

    Soma = 0;
    foreach (DataGridViewRow dr in dataGridView2.Rows)
    Soma += Convert.ToDecimal(dr.Cells[2].Value);
    textBox12.Text = Convert.ToString(string.Format("{0:n}", Soma));
}
    
24.10.2017 / 12:55
0

You can use linq GroupBy to group.

I do not know the name of the attributes of your object but try to change this line:

dataGridView2.DataSource = pesquisa.ToList();

For something like this:

dataGridView2.DataSource = pesquisa.GroupBy(x => x.Data_Venda, x => x.Quantidade).ToList();

I believe this function will group sales dates by adding quantities

    
24.10.2017 / 14:40