我们如何在 C# 整数数组中找到项目数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10906471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can we find items count in the C# integer array?
提问by Ned
I need to find items count in the C# array which type is integer.
我需要在 C# 数组中找到类型为整数的项目数。
What I mean is;
我的意思是;
int[] intArray=new int[10]
int[0]=34
int[1]=65
int[2]=98
Items count for intArray is 3.
intArray 的项目数为 3。
I found the code for strArray below but It doesn't work for int arrays.
我在下面找到了 strArray 的代码,但它不适用于 int 数组。
string[] strArray = new string[50];
...
int result = strArray.Count(s => s != null);
采纳答案by itsme86
Well, first you have to decide what an invalid value would be. Is it 0? If so, you could do this:
好吧,首先您必须确定无效值是什么。是0吗?如果是这样,你可以这样做:
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.
请注意,这仅有效,因为默认情况下,int 数组的元素被初始化为零。如果 0 最终在您的情况下有效,则必须事先用不同的无效值填充数组。
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);
回答by Nick Spreitzer
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, Lengthwill 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-zeroelements in the array, you should do as suggested in some of the other answers.
咳咳。正如我谦虚地指出的那样,Length将返回数组中元素的总数,在您的示例中为 10。如果您正在寻找数组中非零元素的数量,您应该按照建议进行在其他一些答案中。
回答by dckrooney
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.
当您在不指定任何值的情况下初始化整数数组时,C# 会为每个元素分配一个零值。因此,如果零不是数组的有效值,您始终可以对此进行测试。
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.
或者,您可以将数组的元素初始化为在您的上下文中无效的某个值(即,如果负数无效,则初始化为 -1),然后循环遍历数组计算有效元素。
回答by Reed Copsey
While itsme86 provided you a good answer to your actual question, I suspect you may be better off reconsidering how you write this entirely.
虽然itsme86 为您的实际问题提供了一个很好的答案,但我怀疑您最好重新考虑如何完全编写它。
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>:
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 0to the list as an actual value, where counting non-zero elements will not count a zero if it's a valid value.
项目的数量将始终为intList.Count,您可以通过这种方式添加任意数量的项目,而无需担心“分配的大小”,因为列表将根据需要自动增长。如果您将实际值添加0到列表中,它也不会为您提供糟糕的结果,如果非零元素是有效值,则计数非零元素不会计数为零。
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
回答by silijon
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.
如果保证只能按顺序访问数组,则可以通过一点分治来击败完整的迭代 IEnumerable Count(对于较大的数组),例如
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);
回答by Jacob Stern
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.).
如果不是您初始化数组的人(即,您没有将数组值初始化为无效值——空、-1 等)的选项,则之前的解决方案都不是最佳的。
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.
Count()返回 3,实际上已经初始化了 5 个条目。一个例子是从音频文件中读取到缓冲区中的原始字节数组,并且您想知道读取的最后一个元素的索引。
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
另一种不完美但可以满足您要求的替代方法是查找最后一个非零条目,如下所述:Linq - Get the Index of the Last Non-Zero Number of Array

