Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ on ObservableCollection with GroupBy and Sum aggregate

I have the following block of code which works fine;

var boughtItemsToday = (from DBControl.MoneySpent
            bought in BoughtItemDB.BoughtItems
            select bought);

BoughtItems = new ObservableCollection<DBControl.MoneySpent>(boughtItemsToday);

It returns data from my MoneySpent table which includes ItemCategory, ItemAmount, ItemDateTime.

I want to change it to group by ItemCategory and ItemAmount so I can see where I am spending most of my money, so I created a GroupBy query, and ended up with this;

var finalQuery = boughtItemsToday.AsQueryable().GroupBy(category => category.ItemCategory); 

BoughtItems = new ObservableCollection<DBControl.MoneySpent>(finalQuery);

Which gives me 2 errors;

Error 1 The best overloaded method match for 'System.Collections.ObjectModel.ObservableCollection.ObservableCollection(System.Collections.Generic.List)' has some invalid arguments

Error 2 Argument 1: cannot convert from 'System.Linq.IQueryable>' to 'System.Collections.Generic.List'

And this is where I'm stuck! How can I use the GroupBy and Sum aggregate function to get a list of my categories and the associated spend in 1 LINQ query?!

Any help/suggestions gratefully received.

Mark

like image 547
MAO Avatar asked Oct 21 '25 00:10

MAO


1 Answers

.GroupBy(category => category.ItemCategory); returns an enumerable of IGrouping objects, where the key of each IGrouping is a distinct ItemCategory value, and the value is a list of MoneySpent objects. So, you won't be able to simply drop these groupings into an ObservableCollection as you're currently doing.

Instead, you probably want to Select each grouped result into a new MoneySpent object:

var finalQuery = boughtItemsToday
    .GroupBy(category => category.ItemCategory)
    .Select(grouping => new MoneySpent { ItemCategory = grouping.Key, ItemAmount = grouping.Sum(moneySpent => moneySpent.ItemAmount);

BoughtItems = new ObservableCollection<DBControl.MoneySpent>(finalQuery);
like image 194
MikeWyatt Avatar answered Oct 23 '25 15:10

MikeWyatt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!