c# - 使用 LINQ 对货币字典进行分组

标签 c# linq dictionary

我有一个货币字典:

Dictionary<string, string>
        _currencies = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
                        .Select(c => new RegionInfo(c.LCID))
                        .Where(ri => ri != null)
                        .GroupBy(ri => ri.ISOCurrencySymbol)
                        .ToDictionary(x => x.Key, x => x.First().CurrencyEnglishName);

我想将它们分类为一组流行货币和其他货币。

到目前为止我正在这样做,但我不喜欢它:

List<string> popularCurrencies = new List<string>
{
    "GBP", "EUR", "USD", "AUD", "CNY", "INR", "SGD"
};

List<Currency> popular = _currencies
    .Where(kvp => popularCurrencies.Contains(kvp.Key))
    .Select(kvp => new Currency
    {
        Id = kvp.Key,
        Name = kvp.Key + " - " + kvp.Value,
        Category = "Popular"
    })
    .ToList();

List<Currency> other = _currencies
    .Where(kvp => !popularCurrencies.Contains(kvp.Key))
    .Select(kvp => new Currency
    {
        Id = kvp.Key,
        Name = kvp.Key + " - " + kvp.Value,
        Category = "All"
    })
    .ToList();

List<Currency> all = popular.Concat(other).ToList();

public class Currency 
{
  public string Id { get; set; }
  public string Name { get; set; }
  public string Category { get; set; }
}

我想我可以将 2 个 linq 查询和 Concat 合并到 1 行中。

更新:

我向流行货币添加了排序。我想知道是否有一种简单的方法可以对其余的进行排序。

                Dictionary<string, int> popularCurrencies = new Dictionary<string, int>() {
                {"GBP", 1},{"EUR", 2},{"USD", 3},{"AUD", 4},{"CNY", 5},{"INR", 6},{"SGD", 7}
            };
                var all = _currencies.Select(kvp => new Currency
            {
                Id = kvp.Key,
                Name = kvp.Key + " - " + kvp.Value,
                Category = popularCurrencies.Any(c => c.Key == kvp.Key) ? "Popular" : "All"
            }).OrderByDescending(c => c.Category).OrderBy(c => popularCurrencies.ContainsKey(c.Id) ? popularCurrencies[c.Id] : int.MaxValue).ToList();

最佳答案

你可以试试这个:

var all = _currencies.Select(kvp => new Currency
{
    Id = kvp.Key,
    Name = kvp.Key + " - " + kvp.Value,
    Category = popularCurrencies.Any(c => c == kvp.Key) ? "Popular" : "All"    
}).ToList()

添加: 如果您首先想要流行的货币,您可以添加 OrderByDescending:

var all = _currencies.Select(kvp => new Currency
{
    Id = kvp.Key,
    Name = kvp.Key + " - " + kvp.Value,
    Category = popularCurrencies.Any(c => c == kvp.Key) ? "Popular" : "All"    
}).OrderByDescending(c => c.Category).ToList()

关于c# - 使用 LINQ 对货币字典进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29863658/

相关文章:

c# - 升级到 .net 5 程序集缺少框架版本

c# - 获取随机子集合的最佳 LINQ 查询 - Shuffle

c# - 无法创建类型为 'System.Int32[]' 的空常量值。

javascript - 如何从日期时间字段中提取月份?

javascript - 访问 javascript 对象内的数组

c# - 如何控制标签或任何控件PictureBox的位置?

c# - 'L'运算符后缺少操作数

c# - 使用 Angular/C# 上传文件

python - 使用计算值创建字典

scala - 保留插入顺序的不可变 Scala Map 实现