数组的多少元素不为空?
数组是由假定的元素定义的,比如我有像String [] strArray = new String [50]这样的数组; 。
现在从50个元素中只分配了一些元素,剩下的都是null,然后我想要分配元素的数量。
就像这里只分配了30个元素然后我想要那个数字。
您可以使用Enumerable.Count :
string[] strArray = new string[50]; ... int result = strArray.Count(s => s != null);
此扩展方法迭代数组并计算指定谓词适用的元素数。
使用LINQ你可以尝试
int count = strArray.Count(x => x != null);
使用LINQ:
int i = (from s in strArray where !string.IsNullOrEmpty(s) select s).Count();