繁体   English   中英

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

[英]LINQ Anonymous Type to ObservableCollection in Custom Class

我正在努力将一个返回匿名类型的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#比较陌生,需要指向正确的方向 - 如果有人有这方面的任何教程也会有所帮助。

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

BoughtItemDB.BoughtItems.GroupBy(item => item.Category)
       .Select(x => new CatSummary
       {
           CatName = x.Key,
           CatAmount = x.Sum(amt => amt.ItemAmount)
       });

这样,您的查询就会创建一个IEnumerable<CatSummary>而不是IEnumerable<a'> 与其他语言及其鸭子类型不同,仅仅因为您新创建的匿名对象具有CatName和CatAmount属性并不意味着它可以代表实际类型。

不是选择具有new { ...的匿名类型,而是可以选择具有new CatSummary(...的CatSummary实例new 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); 
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM