2011-04-06 27 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));