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...
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 .
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 .
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With