问题已经解决,代码在解释了它想要实现的目标之后。
代码应该能够检索数字重复的次数
首先,代码试图从用户那里获取一个号码: 例如:" 221132"
之后,用户输入一个数字,程序会在第一次输入中找到该数字的次数。
例如:" 2"应返回数字3,因为这是第一次输入中使用该数字的次数。
注意:我想将它们插入List<T>
并从那里开始计算,但是:
我无法使用List(T).Count属性。
我必须使用.FindAll来使用LINQ
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
string InputNo = Console.ReadLine();
List<char> result = InputNo.ToList();
var strResult = result.Select(p => p.ToString()).ToList();
Console.WriteLine("Type the number you want to find and how many times it is repeated");
string findOccurence = Console.ReadLine();
var found = strResult.FindAll(p => p == findOccurence);
int counterOfRepeats = 0;
var intFound = found.ConvertAll(p => Convert.ToInt32(p));
for (int i = 0; i < InputNo.Length; i++)
{
try
{
counterOfRepeats++;
}
catch (Exception)
{
throw;
}
}
Console.WriteLine(counterOfRepeats);
Console.ReadLine();
}
注意:此代码计算字符串重复的次数而不使用.Count
答案 0 :(得分:2)
我知道你说你不能使用Count
属性,Linq的Count()
方法怎么样?
var found = strResult.Count(p => p == findOccurence);
答案 1 :(得分:0)
FindAll返回一个List。您可以通过选中Count属性来获取返回List中的项目数:
var found = strResult.FindAll(p => p== findOccurence).Count;
答案 2 :(得分:0)
您还可以避免使用lambda表达式:
int found = InputNo.ToList().FindAll(findOccurence[0].Equals).Count;