我正在努力将返回匿名类型的 LINQ 语句转换为带有自定义类的 ObservableCollection,我对 LINQ 语句和类定义感到满意,问题(我认为)与我如何实现我的匿名类型和类本身之间的 IQueryable 接口。
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);
}
我得到的错误在最后一行,是
"Argument 1: cannot convert from 'AnonymousType#1' to 'CatSummary'"
我对 c# 比较陌生,需要指出正确的方向——如果有人有任何关于这类事情的教程也会有所帮助。