2014-11-02 103 views
0

是否有可能像這樣迭代字典?通過字典的迭代和做一些東西

  1. 我想指望所有字典項(合計每一個值),
  2. 接下來,針對每一個琴鍵我想利用自己的價值
  3. 然後,我想每一個與和每個鍵值劃分
  4. 而lasty我想每一個輸出從3

乘我做了它,所以它有1項工作,但不知道怎麼做,所以我t適用於字典中的每個項目。

下面是示例代碼1項:

var dic = new Dictionary<string, int>(); 
//this is sum 
double y = 0; 
foreach (var item in dic) 
{ 
    y += item.Value; 
} 
//this is selected item 
double x = 0; 
foreach (var item in dic) 
{    
    if (item.Key == "Smith") 
    { 
     x = item.Value; 
    } 
} 
double z = 0; 
z = x/y; 
Console.WriteLine("Smith/DicSum: " + z); 

現在我想乘個Z(Z各自的在字典中的每個鍵)。

我thiking有關使一個大循環此類似:

for (int i=0; i<y; i++) where y is the sum for all items in dictionary and multiply z's on the end of the loop 

,但我仍然不知道如何抓住所有單獨的值和劃分他們,而不是說他們每個人的特定鍵。

@edit 感謝回答,但檢查我的編輯。我有一個字符串列表,讓我們說

「史密斯是史密斯公司非常酷的成員」

而且我的程序計數史密斯的數量,所以它會顯示X爲兩個。然後我想按所有單詞的數量劃分史密斯(兩個),所以它是2/8 = 0,25。然後我想用這個單詞做這個並且乘以它,所以在這個例子中它將是2/8 * 1/8 * ... * 1/8。所以我想從循環(從字典)中乘以一個重要的數字,而不是固定的數量,這就是造成這個問題的原因。

+1

你的整個第二循環等同於'dic.TryGetValue(「史密斯」,出於X);' – dasblinkenlight 2014-11-02 11:14:09

回答

2
var words = "Smith is very cool member of Smith Company" 
    .Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); 

var dic = new Dictionary<string, double>(); 

foreach (string word in words) 
{ 
    if (dic.ContainsKey(word)) 
     dic[word]++; 
    else 
     dic[word] = 1; 
} 

var sum = dic.Sum(x => x.Value); 
var result = dic.Values.Aggregate(1.0, (current, item) => current * (item/sum)); 
+0

嘿,看看我的編輯:)因爲你通過固定值不是在前循環的值乘以你的榜樣,對不起,如果我問我的問題是錯的。 – 2014-11-02 11:36:48

+0

檢查我更新的回答@ Ken'ichiMatsuyama – dotctor 2014-11-02 11:54:14

+0

謝謝,看着這個,它應該工作,但結果的值是0,0(在調試中檢查),總和是好的,它是8.不知道如何獲得進入當前/項目壽。 – 2014-11-02 12:56:02