描述:
返回一个数字在数组里出现的次数
例如:
var sample = { 1, 0, 2, 2, 3 };
NumberOfOccurrences(0, sample) == 1;
NumberOfOccurrences(2, sample) == 2;
MyCode:
using System;
public class OccurrencesKata
{
public static int NumberOfOccurrences(int x, int[] xs)
{
int count = 0;//定义要返回的出现次数
foreach(int i in xs)//遍历数组里的每个整数,若与x相等,则count+1
{
if(x == i)
count++;
}
return count;
}
}
CodeWar:
using System;
using System.Linq;
public class OccurrencesKata
{
public static int NumberOfOccurrences(int x, int[] xs)
{
return xs.Count(num => num == x);
}
}

本文介绍了一种在C#中统计指定元素在数组中出现次数的方法。提供了两种实现方案:一种是通过遍历数组逐个比较,另一种是利用LINQ查询语法简化代码。这两种方法都实现了相同的功能,即返回指定元素在数组中的出现次数。

被折叠的 条评论
为什么被折叠?



