如何从可观察集合中创建字段 values/counts 的字典?

How to create a dictionary of field values/counts from an observable collection?

我有一个 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 模型不一样 class。

谁能提供查询和转换的建议?

这是供参考的 PiePoint class,其中包含名称和数量:

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;
    }
}

您应该使用 Select(不是 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>(..),因为 CountryRatioCollection 的类型为 ObservableCollection,您不能像示例中那样在此处分配字典。 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);
}