Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display how many times an array element appears

Tags:

arrays

c#

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

like image 734
Momo Avatar asked Aug 07 '12 17:08

Momo


People also ask

How do you count the number of repeats in an array?

To count the duplicates in an array:Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .

How do you check if an element is in an array more than once?

To check if multiple values exist in an array:Use the every() method to iterate over the array of values. On each iteration, use the indexOf method to check if the value is contained in the other array. If all values exist in the array, the every method will return true .

How do you count elements in an array Java?

Java doesn't have the concept of a "count" of the used elements in an array. To get this, Java uses an ArrayList . The List is implemented on top of an array which gets resized whenever the JVM decides it's not big enough (or sometimes when it is too big). To get the count, you use mylist.


1 Answers

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());
like image 126
Reed Copsey Avatar answered Oct 06 '22 00:10

Reed Copsey