如何从可观察的集合中创建字段值/计数字典?

时间:2015-12-05 21:30:12

标签: c# linq dictionary count observablecollection

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

1 个答案:

答案 0 :(得分:1)

您应该使用Select(而不是ToDictionary)并为每个组创建PiePointModel。 IEnumerable的&LT; PiePointModel&GT; piePoints = Customers.GroupBy(i =&gt; i.Country).Select(s =&gt; new PiePointModel() {     名字= s.Key,     金额= s.Count() }); CountryRatioCollection = new ObservableCollection&lt; PiePointModel&gt;(piePoints); 还要注意我使用了:CountryRatioCollection = new ObservableCollection&lt; PiePointModel&gt;(..)因为CountryRatioCollection的类型是ObservableCollection,你不能像在你的例子中那样在这里分配字典。 ObservableCollection的构造函数&lt; T&gt;可以采用IEnumerable&lt; T&gt; - 我在这里用它。 其他方法是使用循环并将新的PiePointModel添加到集合中 CountryRatioCollection = new ObservableCollection&lt; PiePointModel&gt;(); var groups = Customers.GroupBy(i =&gt; i.Country); foreach(var gr in groups) {     PiePointModel piePointModel = new PiePointModel()     {         名字= gr.Key,         金额= gr.Count()     };     CountryRatioCollection.Add(piePointModel); }