使用 C# 评估数据并将其显示在图表控件上

Evaluating data and displaying it on chart control using C#

大家好。

我有一个名为 User 的类型。

public struct User {
    public string ID { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}

我有一个这种类型的数组。

public User[] users;

数组包含:

Index | ID | Name    | Country
0      1    Smith     United States
1      2    Aki       Japan
2      3    Lisa      United States 
3      4    Adam      Sweden
4      5    Geert     Germany
5      6    Hido      Japan

如何在 C# 中找出每个国家/地区的用户数量?

United states - 2
Japan         - 2
Sweden        - 1
Germany       - 1

我想评估此信息以便在图表控件上显示。我确定网上有关于我正在尝试做的事情的信息,但我不知道如何表达它。非常感谢帮助。

提前致谢


更新:

我已完成以下操作并且有效:

    Dictionary<string, int> countries = new Dictionary<string, int>();
    foreach (User user in users) {
        if (!countries.Keys.Contains(user.Country)) {
            countries.Add(user.Country, 1);
        }
        else {
            countries[user.Country]++;
        }
    }

但是,我认为这不是最好的方法...我想看看其他方法。

您可以使用 Linq

var results = from U in users
              group U by U.Country into g
              select new { Country = g.Key, Total = g.count };

如果您使用 group.Key 而不是 group.Country

的 CarbineCoders 答案,它会起作用
public User[] users;

var countryCount= users.ToList().GroupBy(n => n.Country).
                     Select(group =>
                         new
                         {
                             Country= group.Key,
                             Count = group.Count()
                         });