3
I’d like to make a COUNT
using LINQ / LAMBDA, but I’m having difficulties. Can help me?
The idea is to reproduce the following query:
SELECT Conta, Tipo, Documento, Nome, COUNT(0) AS Qtde
FROM TaxaPrecificacao
GROUP BY Conta, Tipo, Documento, Nome
Below are a few ways I tried to do but, of course, they are all wrong.
//Funciona mas a coluna do Count não está sendo calculada
var view = TaxaPrecificacao
.Select(
x => new PrecTxContas
{
Conta = x.Conta,
Tipo = x.Tipo,
Documento = x.Documento,
Nome = x.Nome,
Qtde = 0
});
//Erro de sintaxe
var view = TaxaPrecificacao
.Select(
x => new PrecTxContas
{
Conta = x.Conta,
Tipo = x.Tipo,
Documento = x.Documento,
Nome = x.Nome,
Qtde = x.Count()
});
/*Sintaxe OK mas não compila The type appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order*/
var view = TaxaPrecificacao
.GroupBy(
x => new PrecTxContas
{
Conta = x.Conta,
Tipo = x.Tipo,
Documento = x.Documento,
Nome = x.Nome
})
.Select
(
x => new PrecTxContas
{
Conta = x.Conta,
Tipo = x.Tipo,
Documento = x.Documento,
Nome = x.Nome,
Qtde = x.Count()
});
It is a very specific system, but it would be as follows: I have a table where I register fees for bills. An account can have multiple fees registered in the same table, I would like to count how many fees each account has and display this way: Account Number, Account Type, Document (CPF or CNPJ), Customer Name and the amount of fees. Believe me, in my system this makes sense. But what I’m having difficulty is to reproduce it via LINQ/Lambda. It helped the explanation?
– Rafael
No, it actually didn’t explain anything I intended to know. Your system rule is irrelevant to the question, but come on, what you want is to make a query grouping by these four fields and get the amount of each grouping?
– Jéf Bueno
Yes, as in top SELECT.
– Rafael
A good reading idea: https://answall.com/q/176853/18246
– Jéf Bueno