I am struggling with converting a LINQ statement which returns an anonymous type to an ObservableCollection with a custom class, I’m happy with the LINQ statement, and the class definition, the problem (I think) is to do with how I am implementing the IQueryable interface between my anonymous type and the class itself.
public class CatSummary : INotifyPropertyChanged
{
private string _catName;
public string CatName
{
get { return _catName; }
set { if (_catName != value) { _catName = value; NotifyPropertyChanged("CatName"); } }
}
private string _catAmount;
public string CatAmount
{
get { return _catAmount; }
set { if (_catAmount != value) { _catAmount = value; NotifyPropertyChanged("CatAmount"); } }
}
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify Silverlight that a property has changed.
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
//MessageBox.Show("NotifyPropertyChanged: " + propertyName);
}
}
}
private void GetCategoryAmounts()
{
var myOC = new ObservableCollection<CatSummary>();
var myQuery = BoughtItemDB.BoughtItems
.GroupBy(item => item.ItemCategory)
.Select(g => new
{
_catName = g.Key,
_catAmount = g.Sum(x => x.ItemAmount)
});
foreach (var item in myQuery) myOC.Add(item);
}
The error I am getting is on the last line and is
"Argument 1: cannot convert from 'AnonymousType#1' to 'CatSummary'"
I’m relatively new to c# and need pointing in the right direction – if anyone has any tutorials on this sort of thing that would help as well.
This is because the anonymous object you are creating has no type relationship with
CatSummary. If you want to add those items into your ObservableCollection, you will need to construct aCatSummarylike so:This way, your query creates an
IEnumerable<CatSummary>instead ofIEnumerable<a'>. Unlike other languages and their duck typing, just because your newly created anonymous object has a CatName and CatAmount property does not mean it can stand in for the actual type.