C# LINQ匿名类型到自定义类中的ObservableCollection

C# LINQ匿名类型到自定义类中的ObservableCollection,c#,wpf,linq,observablecollection,C#,Wpf,Linq,Observablecollection,我正在努力将返回匿名类型的LINQ语句转换为带有自定义类的ObservableCollection,我对LINQ语句和类定义感到满意,我认为问题在于如何在匿名类型和类本身之间实现IQueryable接口 public class CatSummary : INotifyPropertyChanged { private string _catName; public string CatName { get { return _catName; }

我正在努力将返回匿名类型的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);
}
我得到的错误在最后一行,是 参数1:无法从“AnonymousType1”转换为“CatSummary”


我对c比较陌生,需要指出正确的方向-如果有人有关于这类内容的教程,也会有帮助。

这是因为您创建的匿名对象与CatSummary没有类型关系。如果要将这些项添加到ObservableCollection中,则需要构建如下CatSummary:


这样,您的查询将创建IEnumerable而不是IEnumerable而不是使用new{…,选择匿名类型,您可以使用new CatSummary…或使用任何其他可用于构造CatSummary实例的方法来选择CatSummary实例。

尝试以下操作:

 foreach (var item in myQuery) 
 {
     // You will need to create a new constructor
     var catsummary = new CatSummary(item.CatName, item.CatAmount);
     myOC.Add(catsummary); 
  }

这项工作做得很好,我一步一步地看代码,就知道为什么会这样。非常感谢。我现在正在努力进行WPF绑定,如何将XAML对象绑定到我的自定义类?我遇到的错误是BindingExpression路径错误…在上找不到属性?
 foreach (var item in myQuery) 
 {
     // You will need to create a new constructor
     var catsummary = new CatSummary(item.CatName, item.CatAmount);
     myOC.Add(catsummary); 
  }