2015-12-05 37 views
0

我有一个ObservableCollection<CustomerModel> Customers,即持有国家字段。我想要做的是,创建一个PiePointModel类型的可观察集合。为了存储国家名称和该国名称的出现次数。如何从可观察集合创建字段值/计数字典?

因此,我设置了一个ObservableCollection<PiePointModel> CountryRatioCollection,其中PiePoint包含名称和金额。

然后我试图为该集合分配给我的客户,将其转换为辞典保持所需的值:

CountryRatioCollection = new ObservableCollection<PiePointModel>(); 
      CountryRatioCollection = Customers.GroupBy(i => i.Country).ToDictionary(g => g.Key, g => g.Count()); 

但我得到一个错误,指出这不能被隐式转换:

Error 2 Cannot implicitly convert type 'System.Collections.Generic.Dictionary<string,int>' to 'System.Collections.ObjectModel.ObservableCollection<MongoDBApp.Models.PiePointModel>' 

我知道这是因为Dictionary类型与我的PiePoint模型类不一样。

任何人都可以提供查询和转换的建议吗?

这是供参考PiePoint类,保存名称和金额:

public class PiePointModel 
{ 
    public string Name { get; set; } 
    public int Amount { get; set; }  
} 

这是持有该国领域的CustomerModel:

public class CustomerModel 
{ 
    [BsonId] 
    public ObjectId Id { get; set; } 

    [BsonElement("firstName")] 
    public string FirstName { get; set; } 

    [BsonElement("lastName")] 
    public string LastName { get; set; } 

    [BsonElement("email")] 
    public string Email { get; set; } 

    [BsonElement("address")] 
    public string Address { get; set; } 

    [BsonElement("country")] 
    public string Country { get; set; } 

    public override string ToString() 
    { 
     return Country; 
    } 
} 
+0

边注:行'CountryRatioCollection =新的ObservableCollection ();'是无用的。 –

回答

1

您应该使用选择(不ToDictionary)并为每个组创建PiePointModel。

IEnumerable<PiePointModel> piePoints = Customers.GroupBy(i => i.Country).Select(s => new PiePointModel() 
{ 
    Name = s.Key, 
    Amount = s.Count() 
}); 
CountryRatioCollection = new ObservableCollection<PiePointModel>(piePoints); 

还要注意,我用:CountryRatioCollection = new ObservableCollection<PiePointModel>(..)因为CountryRatioCollectionObservableCollection类型的,你不能在你的例子这里分配字典等。 ObservableCollection<T>的构造函数可以采取IEnumerable<T> - 我在这里使用它。

其它方法是使用循环和添加新PiePointModel至收集

CountryRatioCollection = new ObservableCollection<PiePointModel>(); 
var groups = Customers.GroupBy(i => i.Country);  
foreach(var gr in groups) 
{ 
    PiePointModel piePointModel = new PiePointModel() 
    { 
     Name = gr.Key, 
     Amount = gr.Count() 
    }; 
    CountryRatioCollection.Add(piePointModel); 
} 
+0

好吧,有道理,使用IEnumerable。顺便说一句,你错过了a)在piePointModel的右括号。 –