gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:58:46 25 4
gpt4 key购买 nike

我有一本货币字典:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com