简体   繁体   中英

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. 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.

I have done the following but don`t know how to put it in the foreach/if statement...

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 . I recommend looking at the C# LINQ samples section on Count and GroupBy for guidance.

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. In the example below, dict[d] refers to an element by its value. For example 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 . You can get the count of each item by accessing dict[d] , where d is some integer value from your original list.

The LINQ answers are nice, but if you're trying to do it yourself:

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()

{

        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();

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM