Reputation: 4444
I've groupted data which now looks like this:
<tr>
<th>Id</th>
<th>Type</th>
<th>Amount</th>
</tr>
<tr>
<td>1</td>
<td>Delivered</td>
<td>100</td>
</tr>
<tr>
<td>2</td>
<td>Sent</td>
<td>150</td>
</tr>
<tr>
<td>3</td>
<td>Received</td>
<td>110</td>
</tr>
<tr>
<td>4</td>
<td>Delivered</td>
<td>79</td>
</tr>
<tr>
<td>5</td>
<td>Sent</td>
<td>30</td>
</tr>
Here's the code how I get it:
var query = await _context.product.AsNoTracking().Where(x => (x.productDate.Date >= DateTime.Now.AddDays(-30) && x.productDate.Date <= DateTime.Now.Date).ToListAsync();
if (query == null) return null;
var data = query.GroupBy(x => x.productStatusId)
.Select(product => new productsChartDTO
{
Type =
(
product.FirstOrDefault().productStatusId == (int)Enums.productStatus.Delivered || product.FirstOrDefault().productStatusId == (int)Enums.productStatus.InProcess ? "Delivered" :
product.FirstOrDefault().productStatusId == (int)Enums.productStatus.Sent || product.FirstOrDefault().productStatusId == (int)Enums.productStatus.InProcess ? "Sent" :
product.FirstOrDefault().productStatusId == (int)Enums.productStatus.Received ? "Received" : "Unknown"
),
Amount = product.Sum(x => x.Amount)
});
return data;
As it's possible to seen guys, even if I grouping by productStatusId
, if productStatus
is in 'InProcess
' or in 'Delivered
' there will be Type "Delivered
", so after this query
I'm seeing results with type "Delivered
" twice as I posted in example.
I think after this execution I should be grouping data again?
How could I achieve this ?
Is it possible to continue grouping on this query or there should be another one which would group again?
Thanks
Cheers
Upvotes: 0
Views: 244
Reputation: 169150
Just move your logic to the GroupBy
method and return a type string
instead of an int
from it:
var data = query
.GroupBy(x => x.productStatusId == (int)Enums.productStatus.Delivered || x.productStatusId == (int)Enums.productStatus.InProcess ? "Delivered" :
x.productStatusId == (int)Enums.productStatus.Sent || x.productStatusId == (int)Enums.productStatus.InProcess ? "Sent" :
x.productStatusId == (int)Enums.productStatus.Received ? "Received" : "Unknown")
.Select(product => new productsChartDTO
{
Type = product.Key,
Amount = product.Sum(x => x.Amount)
});
Upvotes: 1
Reputation: 9499
Instead of
.GroupBy(x => x.productStatusId)
Do
.GroupBy(x => {
if (new [] { (int)Enums.productStatus.InProcess, (int)Enums.productStatus.Delivered }.Contains(x.productStatusId) {
return "Delivered";
} else if ((int)Enums.productStatus.Sent == x.productStatusId) { // Note: your code had 'InProcess' twice
return "Sent";
} else if ((int)Enums.productStatus.Received == x.productStatusId) {
return "Received";
}
return "Unknown";
})
Upvotes: 0