簡體   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