将字典转换为列表

3

我有一个带有以下签名的字典:

Dictionary<decimal, int>

里面的项目看起来像这样:

90, 2
60, 3
30, 4
20, 1

我需要将其扩展为具有以下特征的列表:

List<double>

里面的项目看起来像这样:

90
90
60
60
60
30
30
30
30
20

有没有什么优雅高效的方法来实现这个?
4个回答

8

请尝试以下方法:

dictionary
  .SelectMany(pair => Enumerable.Repeat((double)pair.Key, pair.Value))
  .OrderByDescending(x => x)
  .ToList();

我不确定OrderBy是否是要求的一部分。 - spender
@spender,OP没有指定顺序,但是按照元素的顺序放置,所以我在确保我的输出与之匹配时出现了错误。 - JaredPar
是的,我想鉴于字典的枚举顺序未定义,OP需要注意在SelectMany之前或之后的排序(就像您所做的那样)。 - spender
我希望我能够+多于1的内容。很棒的答案。 - Adam Rackis

5
dictionary
    .SelectMany(kvp => Enumerable.Repeat(Decimal.ToDouble(kvp.Key), kvp.Value))
    .ToList()

1
foreach (var pair in dict)
    for (int i=0;i<pair.Value;i++)
        list.Add((double)pair.Key);

0
public static IEnumerable<T> Blowout<T>(T value, int length)
{
    for (int i = 0; i < length; i++) yield return value;
}

dictionary
    .SelectMany(pair => Blowout((double)pair.Key, pair.Value));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接