在 C# 中,我有一些值 > 0 和一些等于 0 的小数变量。我从 C# winform 上的不同文本框的数量中获得这些小数。
计算其中有多少值 > 0 的最佳做法是什么?
如果计数 > 12,则具有最低值的变量(仅非零值)应更改为 0
不要使用一长串小数,使用它们的数组:
decimal[] values = new decimal[17];
/*Populate the values array with data*/
int CountOfMoreThanZero = values.Count(v => v > 0);
它不是面向对象软件工程的获奖作品,但它应该可以完成这项工作:
static void Main(string[] args)
{
var seq = Enumerable.Range(0, 12).Select(i => (decimal)i);
Console.WriteLine(GetGreaterThanZero(seq));
var arr = seq.ToArray();
SetMinNull(arr);
foreach(var n in arr)
Console.WriteLine(n);
}
static int GetGreaterThanZero(IEnumerable<decimal> numbers)
{
return numbers.Count(n => n > 0);
}
static void SetMinNull(decimal[] numbers)
{
decimal min = numbers.Min();
// edit: credits to daniel for this loop
for(int i = 0; i < numbers.Length; i++)
{
if(numbers[i] == min) numbers[i] = 0;
}
}
它使用集合。但是,我建议您也使用它们。使用大量编号不同的值是一种代码味道,我猜几乎不太方便。