2013-03-06 82 views
3

我有一個包含重複值的數組。我需要顯示在數組中找到每個值的次數。如何顯示數組值在數組中的時間?

讓我們說,我有8個值的數組,數組= {1,2,3,1,1,2,6,7} 我需要的輸出爲:

1 was found 3 times 
2 was found 2 times 
3 was found 1 time 
6 was found 1 time 
7 was found 1 time 

這裏是我的代碼。現在,我將數組中的每個值保存到一個變量中,然後遍歷數組以檢查值是否存在,然後將其打印出來。

int[] nums = { 2, 4, 14, 17, 45, 48, 5, 6, 16, 25, 28, 33, 17, 26, 35, 44, 46, 49, 5, 6, 20, 27, 36, 45, 6, 22, 23, 24, 33, 39, 4, 6, 11, 14, 15, 38, 5, 20, 22, 26, 29, 47, 7, 14, 16, 24, 31, 32 }; 
      for (int i = 0; i < nums.Length; i++) 
      { 
       int s = nums[i]; 
       for (int j = 0; j < nums.Length; j++) 
       { 
        if (s == nums[j]) 
        { 
         Console.WriteLine(s); 
        } 
       } 

      } 

預先感謝

回答

13
foreach(var grp in nums.GroupBy(x => x).OrderBy(grp => grp.Key)) { 
    Console.WriteLine("{0} was found {1} times", grp.Key, grp.Count()); 
} 

GroupBy將所有的值成組使用本身數作爲密鑰(通過x => x)。對於每個獨特的值,我們將有一個不同的組,其中包含一個或多個值。 OrderBy確保我們按鍵順序報告組(通過grp => grp.Key)。最後,Count告訴我們在Key(原始值,如果您記得的話)標識的組中有多少物品。

+0

現在這就是我所說的真棒! – Aditi 2013-03-06 11:48:58

+1

這將是很好的解釋OP你在這裏做什麼......不錯的答案然而。 – Th0rndike 2013-03-06 11:49:56

+1

@ Th0rndike更好? – 2013-03-06 11:52:41

2

如何使用.Key.Count分組訂購他們?

foreach(var g in nums.GroupBy(x => x).OrderBy(g => g.Key)) 
{ 
    Console.WriteLine("{0} was found {1} times", g.Key, g.Count()); 
} 

這是DEMO

0

您可以通過Enumerable.GroupBy進行處理。我建議查看Count和GroupBy上的C# LINQ samples部分以獲取指導。

在你的情況,這可能是:

int[] values = new []{2, 4, 14, 17, 45, 48, 5, 6, 16, 25, 28, 33, 17, 26, 35, 44, 46, 49, 5, 6, 20, 27, 36, 45, 6, 22, 23, 24, 33, 39, 4, 6, 11, 14, 15, 38, 5, 20, 22, 26, 29, 47, 7, 14, 16, 24, 31, 32}; 

var groups = values.GroupBy(v => v); 
foreach(var group in groups) 
    Console.WriteLine("{0} was found {1} times", group.Key, group.Count()); 
+0

非常感謝,它工作。 – Momo 2013-03-06 11:57:38

+0

把標記放在任何你喜歡的答案.bcs其他人的幫助 – 2013-03-06 11:59:43

0

你跟純教育工作的陣列? C#提供了Collections,它們提供了很多方便的功能來解決這些問題。 System.Collections.Dictionary提供您正在尋找的功能。添加一個項目,如果它不存在並作出反應,當一個密鑰已被添加。

using System.Collections.Generic; 

Dictionary<int,int> dic = new Dictionary<int, int>(); 
if(!dic.Keys.Contains(key)) 
    //add key and value 
else 
    //get key and add value 

請參閱MSDN爲此。

+0

非常感謝你 – Momo 2013-03-06 11:57:00