7

I need to find items count in the C# array which type is integer.

What I mean is;

int[] intArray=new int[10]
int[0]=34
int[1]=65
int[2]=98

Items count for intArray is 3.

I found the code for strArray below but It doesn't work for int arrays.

string[] strArray = new string[50];
...
int result = strArray.Count(s => s != null);
1
  • 1
    Is there a reason you're using an array instead of a List<int>? Commented Jun 6, 2012 at 0:13

6 Answers 6

8

Well, first you have to decide what an invalid value would be. Is it 0? If so, you could do this:

int result = intArray.Count(i => i != 0);

Note that this only works because, by default, elements of an int array are initialized to zero. You'd have to fill the array with a different, invalid value beforehand if 0 ends up being valid in your situation.

Another way would be to use a nullable type:

int?[] intArray = new int?[10];
intArray[0] = 34;
intArray[1] = 65;
intArray[2] = 98;

int result = intArray.Count(i => i.HasValue);
Sign up to request clarification or add additional context in comments.

11 Comments

only issue is this will tell you how many has value, not the sequence. if intArray[1] is null but intArray[3] is not, you cannot assume that the first 3 items got values, but the count will return 3
That is true, but the OP never indicated the values all had to be in sequence. The OP just referred to it as "items count", and their example might have just happened to be in sequence.
This is useful, but is going to be problematic if zero is a valid value within the array...
@ReedCopsey Exactly as I pointed out in the first line of my answer. :)
@itsme86 Yes - but if zero isn't an invalid value, this technique doesn't work at all. Your line suggests any invalid value (ie: -999) would work, which is not true unless you explicitly initialzie the array to the invalid value in advance. Zero happens to work just because the array is automatically initialized with zero values, but if zero is not invalid, then it breaks down. (My answer provides a different alternative that works in this case... Though I did vote yours up because it's reasonable, and directly answers the question asked.)
|
3

While itsme86 provided you a good answer to your actual question, I suspect you may be better off reconsidering how you write this entirely.

If this is your goal, I would recommend thinking about this differently. Instead of allocating a fixed size array, and only assigning specific values to it, you might want to consider using a List<int>:

List<int> intList = new List<int>();

intList.Add(34);
intList.Add(65);
intList.Add(98);

The number of items will always be intList.Count, and you can add as many items as you wish this way, without worry about the "allocated size", since the list will automatically grow as needed. It also won't provide you bad results if you add 0 to the list as an actual value, where counting non-zero elements will not count a zero if it's a valid value.

Note that you can also access the items by index, just like you do with an array:

int secondValue = intList[1]; // Access like you do with arrays

1 Comment

3 years later, I find this answer to be the correct one, as the selected answer does not solve for the case where a 0 is a probable (and expected!) value for one of the elements!
2
int[] intArray=new int[3]  // Edit: Changed this to 3 to make my answer work. :)
int[0]=34
int[1]=65
int[2]=98

int count = intArray.Length; // <-- Is this what you're after?

Edit:

Ahem. As was so humbly pointed out to me, Length will return the total number of elements in the array, which in your example would have been 10. If you are looking for the number of non-zero elements in the array, you should do as suggested in some of the other answers.

3 Comments

@bonesbrigade I did? I don't see any edits on the original question from me? What are you talking about?
Line 1: // Edit: Changed this to 3 to make my answer work. :)
@bonesbrigade: Oh gawd. What you're apparently trying to communicate is that I modified my answer, not the question. Now what in the world is wrong with that?
0

When you initialize an integer array without specifying any values, C# assigns a value of zero to every element. So if zero isn't a valid value for your array, you could always test for that.

Alternatively, you could initialize the elements of your array to some value that is invalid in your context (ie if negative numbers aren't valid, initialize to -1), and then loop through the array counting the valid elements.

Comments

0

If the array is guaranteed to only be accessed in sequence, you can beat the full iterative IEnumerable Count (for larger arrays) with a little divide and conquer, e.g.

static int DivideCount(int[] arr, int idx, int bottom, int top)
{
    if (idx <= 0)
        return 0;
    else if (idx >= arr.Length - 1)
        return arr.Length;
    else if (arr[idx] == 0 && arr[idx - 1] != 0)
        return idx;
    else if (arr[idx] == 0 && arr[idx - 1] == 0)
        return DivideCount(arr, bottom + ((idx - bottom) / 2), bottom, idx);
    else if (arr[idx] != 0 && arr[idx - 1] != 0)
        return DivideCount(arr, top - ((top - idx) / 2), idx, top);
    else
        return -1;  // hello compiler
}



int[] intArray = new int[10];
intArray[0] = 35;
intArray[1] = 65;
intArray[2] = 98;

var count = DivideCount(intArray, intArray.Length / 2, 0, intArray.Length);

Comments

0

None of the previous solutions are optimal if someone other than you initialized the array (i.e. you don't have the option of initializing the array values to invalid values -- null, -1, etc.).

Suppose you have an array:

var arr = new[] {0, 10, 18, 0, 20, 0, 0, 0, 0, 0, 0, 0};

If you simply count the number of zero entries:

int result = arr.Count(i => i != 0);

Count() returns 3, when in reality 5 entries have been initialized. An example would be an array of raw bytes that were read out of an audio file into a buffer, and you want to know the index of the last element that was read.

An alternative that isn't perfect but could do what you're looking for is to look for the last non-zero entry, as described here: Linq - Get the Index of the Last Non-Zero Number of Array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.