Reputation: 165
In C#, I have some decimal variables with values > 0 and some equal to 0. I get these decimals from number of different text boxes on a C# winform.
What is best practice for counting how many of them have values > 0?
If the count is > 12, The variables that have the lowest values, (only the values that are non-zero) should be changed to 0
Upvotes: 0
Views: 1105
Reputation: 12521
It isn't an award-winning piece of object-oriented software engineering, but it should do the job:
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;
}
}
It uses collections. I'd recommend you to use them too, however. Using a lot of numbered different values is a code smell, and barely too handy I guess.
Upvotes: 0
Reputation: 13864
Don't use a long list of decimals, use an array of them:
decimal[] values = new decimal[17];
/*Populate the values array with data*/
int CountOfMoreThanZero = values.Count(v => v > 0);
Upvotes: 6