我有一个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;
}
}
边注:行'CountryRatioCollection =新的ObservableCollection();'是无用的。 –