[英]How to display how many times an array element appears
I am new to C# and hope I can get some help on this topic. 我是C#的新手,希望我能在这个主题上得到一些帮助。 I have an array with elements and I need to display how many times every item appears. 我有一个包含元素的数组,我需要显示每个项目出现的次数。
For instance, in [1, 2, 3, 4, 4, 4, 3]
, 1
appears one time, 4
appears three times, and so on. 例如,在[1, 2, 3, 4, 4, 4, 3]
, 1
出现一次, 4
出现三次,依此类推。
I have done the following but don`t know how to put it in the foreach/if statement... 我做了以下但不知道如何把它放在foreach / if语句中......
int[] List = new int[]{1,2,3,4,5,4,4,3};
foreach(int d in List)
{
if("here I want to check for the elements")
}
Thanks you, and sorry if this is a very basic one... 谢谢你,对不起,如果这是一个非常基本的...
You can handle this via Enumerable.GroupBy . 您可以通过Enumerable.GroupBy处理此问题。 I recommend looking at the C# LINQ samples section on Count and GroupBy for guidance. 我建议查看Count和GroupBy上的C#LINQ示例部分以获取指导。
In your case, this can be: 在您的情况下,这可以是:
int[] values = new []{1,2,3,4,5,4,4,3};
var groups = values.GroupBy(v => v);
foreach(var group in groups)
Console.WriteLine("Value {0} has {1} items", group.Key, group.Count());
You can keep a Dictionary
of items found as well as their associated counts. 您可以保留找到的项目Dictionary
及其相关计数。 In the example below, dict[d]
refers to an element by its value. 在下面的示例中, dict[d]
通过其值引用元素。 For example d = 4
. 例如d = 4
。
int[] List = new int[]{1,2,3,4,5,4,4,3};
var dict = new Dictionary<int, int>();
foreach(int d in List)
{
if (dict.ContainsKey(d))
dict[d]++;
else
dict.Add(d, 1);
}
When the foreach
loop terminates you'll have one entry per unique value in dict
. 当foreach
循环终止时, dict
每个唯一值都有一个条目。 You can get the count of each item by accessing dict[d]
, where d
is some integer value from your original list. 您可以通过访问dict[d]
来获取每个项目的计数,其中d
是原始列表中的某个整数值。
The LINQ answers are nice, but if you're trying to do it yourself: LINQ答案很好,但是如果你想自己做的话:
int[] numberFound = new int[6];
int[] List = new int[] { 1, 2, 3, 4, 5, 4, 4, 3 };
foreach (int d in List)
{
numberFound[d]++;
}
var list = new int[] { 1, 2, 3, 4, 5, 4, 4, 3 };
var groups = list.GroupBy(i => i).Select(i => new { Number = i.Key, Count = i.Count() });
private static void CalculateNumberOfOccurenceSingleLoop() private static void CalculateNumberOfOccurenceSingleLoop()
{ {
int[] intergernumberArrays = { 1, 2, 3, 4, 1, 2, 4, 1, 2, 3, 5, 6, 1, 2, 1, 1, 2 };
Dictionary<int, int> NumberOccurence = new Dictionary<int, int>();
for (int i = 0; i < intergernumberArrays.Length; i++)
{
if (NumberOccurence.ContainsKey(intergernumberArrays[i]))
{
var KeyValue = NumberOccurence.Where(j => j.Key == intergernumberArrays[i]).FirstOrDefault().Value;
NumberOccurence[intergernumberArrays[i]] = KeyValue + 1;
}
else
{
NumberOccurence.Add(intergernumberArrays[i], 1);
}
}
foreach (KeyValuePair<int, int> item in NumberOccurence)
{
Console.WriteLine(item.Key + " " + item.Value);
}
Console.ReadLine();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.