如何搜索一维数组中重复元素的个数?
比如 int [] arr={12,12,12,13,13,14,14,14,14,0}
12的个数有3个
13的个数有2个
14的个数有4个
0的个数有1个
如何编程搜索呢?
字符串数组
string [] arr={"工人","解放军","工人","老师","解放军"}
"工人"的个数2个
"解放军"的个数2个
"老师"的个数1人
如何编程搜索呢?
比如 int [] arr={12,12,12,13,13,14,14,14,14,0}
12的个数有3个
13的个数有2个
14的个数有4个
0的个数有1个
如何编程搜索呢?
字符串数组
string [] arr={"工人","解放军","工人","老师","解放军"}
"工人"的个数2个
"解放军"的个数2个
"老师"的个数1人
如何编程搜索呢?
Dictionary<int, int> dic = new Dictionary<int, int>();
foreach (int i in arr)
{
if (dic.ContainsKey(i))
dic[i] = dic[i] + 1;
else
dic.Add(i, 1);
}
//查看结果
foreach (int j in dic.Keys)
{
richTextBox2.Text += j.ToString() + "的个数有: " + dic[j] + "个\n";
}
int[] arr = { 12, 12, 12, 13, 13, 14, 14, 14, 14, 0 };
var query =
from a in arr
group arr by a into g
orderby g.Count()
select new
{
g.Key,
count = g.Count()
};
foreach (var i in query)
{
Console.WriteLine("{0}出现{1}次", i.Key, i.count);
}
HashTable hs= new HashTable();
if(arr.Length>0)
{
int c=0;
for (int i=0;i<arr.Length;i++)
{
if(arr[0]==arr[i])
{
Array.Clear(arr,i,1);
c++;
}
hs.Add(arr[0],c);
}
foreach (DictionaryEnty myDe in hs)
{
Console.WriteLine("\t{0}\t{1}",myDe.Key,myDe.Value);
}
Console.ReadLine();
Console.WriteLine("\t{0}的个数有\t{1}个",myDe.Key,myDe.Value);
static void Main(string[] args)
{
int[] arr = { 12, 12, 12, 13, 13, 14, 14, 14, 14, 0 };
ShowElementCount(arr);
string[] arr2 = { "工人", "解放军", "工人", "老师", "解放军" };
ShowElementCount(arr2);
Console.WriteLine();
ShowElementCountWithLinq(arr);
ShowElementCountWithLinq(arr2);
} /// <summary>
/// 非Linq版
/// </summary>
/// <param name="array"></param>
public static void ShowElementCount(Array array)
{
Dictionary<object, int> dic = new Dictionary<object, int>();
foreach (object o in array)
{
if (!dic.ContainsKey(o))
dic.Add(o, 1);
else
dic[o]++;
}
foreach (object o in dic.Keys)
Console.WriteLine("{0}出现了{1}次", o, dic[o]);
} /// <summary>
/// Linq版
/// </summary>
/// <param name="array"></param>
public static void ShowElementCountWithLinq(Array array)
{
var elementCount = from o in array.Cast<object>()
group o by o into oGroup
select new
{
oGroup.Key,
count = oGroup.Count()
};
foreach (var element in elementCount)
Console.WriteLine("{0}出现了{1}次", element.Key, element.count);
}
Dictionary有个属性,能通过键找到值.
还有个问题,如何通过值找到相应的键,
请教各位老师!!!
int[] arr = { 12, 12, 12, 13, 13, 14, 14, 14, 14, 0 };
Dictionary<object, int> dic = new Dictionary<object, int>();
foreach (object o in arr)
{
if (!dic.ContainsKey(o))
dic.Add(o, 1);
else
dic[o]++;
}
foreach (object o in dic.Keys)//非Linq版
{
if (dic[o] == 3)
Console.WriteLine("值为3的键有{0}", o);
} //Linq版
var keys = from item in dic
where item.Value == 3
select item.Key;
foreach (var key in keys)
Console.WriteLine("值为3的键有{0}", key);