Reputation: 225
I have defined a class like this:
public class GroupedItem
{
public DateTime _Date { get; set; }
public int Sales { get; set; }
public float TransactionPrice { get; set; }
public string Seller { get; set; }
// Part used for calculation
public float BestSellerAveragePrice { get; set; }
public float MinPrice { get; set; }
public float MaxPrice { get; set; }
}
And then I have filled it with a list of GroupedItem type like following:
List<GroupedItem> _groupedItems = new List<GroupedItems>();
Lets say the list has 300 items whose only initialized values are first four properties like above. The part with min, max and average price I'm going to fill after a group by statement like following:
ViewBag.PriceAnalytics = _groupedItems.GroupBy(x => x.Seller).Select(gi => new GroupedItem() { MinPrice = x. }).ToList();
As you can see I'm grouping by seller property to get all sales for users which sold something and by the specific price.
What I'm trying to do is to first sum all these prices that they sold, and then take out an min and max value. So if the input values were:
Seller Mike, 21.12.2016, 1 sale, 48$
Seller Mike, 21.12.2016, 1 sale, 24$
Seller Mike, 21.12.2016, 1 sale, 29$
Seller Jenna, 21.12.2016, 1 sale, 20$
Seller Jenna, 21.12.2016, 1 sale, 39$
Seller Jenna, 21.12.2016, 1 sale, 56$
Seller Josh, 21.12.2016, 1 sale, 10$
Seller Josh, 21.12.2016, 1 sale, 28$
Seller Josh, 21.12.2016, 1 sale, 39$
The desired output would be:
Seller Mike, 21.12.2016, 3 sales, 101$
Seller Jenna, 21.12.2016, 3 sales, 115$
Seller Josh, 21.12.2016, 3 sales, 77$
After a first group by.. Now I would have all sellers and their total sales with their total earnings.
Now what I need to do with these 3 values:
101, 115, 77
Min price would be 77$, and max price would be 115$
How can do this with LINQ?
Upvotes: 0
Views: 1789
Reputation: 6948
You could also get a list of summarized data with a LINQ query:
var data = (from gp in test
group gp by gp.Seller into g
select new GroupedItem
{
Seller = g.Key,
_Date = g.First()._Date,
Sales = g.Sum(x => x.Sales),
TransactionPrice = g.Sum(x => x.TransactionPrice)
}).ToList();
var best = data.Max(x => x.TransactionPrice);
var worst = data.Min(x => x.TransactionPrice);
Upvotes: 2
Reputation: 62488
you are almost there, after grouping on seller, you need to process each group one by one, see :
List<GroupedItem> result = new List<GroupedItem>();
var groupedResult = _groupedItems.GroupBy(x=>x.Seller);
foreach(var grouping in groupedResult)
{
var row = grouping.First();
row.TransactionPrice = grouping.Sum(x=>x.TransactionPrice);
row.Sales = grouping.Sum(x=>x.Sales);
result.Add(row);
}
Upvotes: 1