Question

EDIT Question originally: Count and total repeating occurrences of a number in a specific array position - i.e. how many 0's in array[34].

Changed to Count and total repeating occurrences of a unique values in DataGridView column

This is because I feel I asked the wrong question and the new one gives a more accurate sense of what I was looking for

This is pretty much exactly what I wanted: http://www.codeproject.com/Tips/421557/Counting-Unique-Products-in-a-DataGridView-and-Dis

I obviously could have described the question much better.

I have a byte array populated with a random-access file, I would like to count the amount of times, let's say, 0 or 127 occurs in a certain position. At the moment I can count the amount of successful matches to several numbers but the problem is totalling it. I have tried this: (unsurprisingly does not work)

if (array[34] == 0)
{
    Label_a.Text = "abc";
}

int res_a = Regex.Matches(array[34].ToString(), "0").Count;

If I create a MessageBox with res_a, it recognises if it's a 0 or not by displaying a set message. But I would like to count and total the amount of occurrences in the background where the data totalled is going to be populated into a chart. General layout of current code:

// FileStream
// BinaryReader
// While length of file is larger than 0
// FileStream.Seek
// Foreach loop for array
// GET COUNT AND TOTAL HERE!

For example, I import a file with 4 records with different status' where status code 127 is repeated 3 times and 0 is just once. I want to get THIS information - how many times it has occurred!

enter image description here

Another example, this file has 12 records where status code 127 is repeated 6 times and 0 is 6 too:-

enter image description here

Was it helpful?

Solution

Based on your comment to L.B., I understand that you want to count the number of occurences of each "status" value, so I would try something like this:

int[] vals = new int[10] { 1, 1, 2, 2, 3, 3, 3, 4, 4, 1 };
var res = vals.GroupBy(v => v).ToDictionary(g => g.Key, g => g.Count());

res now holds a Dictionary where each KeyValuePair has a Key representing a Status code, and a Value representing the number of time this Status code is in the array.

You can now test a Status code's number of appearance like this:

int Code1;
res.TryGetValue(1, out Code1); // testing for Status code 1

And so on.

Cheers

OTHER TIPS

Couldn't you do something like this?

var countOf0s = array.Count(x => x == 0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top