2011-04-06 54 views
3

我有这个签名的字典:吹字典出的列表

Dictionary<decimal, int> 

里面的物品是这样的:

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

我要吹这一点具有此列表签名:

List<double> 

项目里面应该是这样的:

90 
90 
60 
60 
60 
30 
30 
30 
30 
20 

有关如何以优雅高效的方式做到这一点的任何想法?

回答

8

请尝试以下

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

我不知道的排序依据是要求的一部分。 – spender 2011-04-06 23:38:26

+0

@spender,OP没有具体说明,但是按顺序放置了这些元素,所以我错误地确定了我的匹配输出。 – JaredPar 2011-04-06 23:39:24

+0

是的,我想假设没有定义字典的枚举顺序,OP将需要注意SelectMany之前或之后的顺序(如你所做的那样)。 – spender 2011-04-06 23:44:11

1
foreach (var pair in dict) 
    for (int i=0;i<pair.Value;i++) 
     list.Add((double)pair.Key); 
5
dictionary 
    .SelectMany(kvp => Enumerable.Repeat(Decimal.ToDouble(kvp.Key), kvp.Value)) 
    .ToList() 
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));