I'm newbie in C#. My problem is, I have 19 double values. Some of them are equals to zero. I want to eliminate these zeros and find the maximum one from remaining values. How can i do that ? My code includes only double values.
double m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15, m16, m17, m18, m19;
m1 = 200;
m2 = 1000;
m3 = 1500;
m4 = 2000;
m5 = 4000;
m6 = 7000;
m7 = 10000;
m8 = 12000;
m9 = 14000;
m10 = 16000;
m11 = 0;
m12 = 0;
m13 = 0;
m14 = 0;
CodePudding user response:
Using individual variables for each value makes the task very tedious because you must write code for every one of these variables. Insert the values into a collection.
If you have a fixed set of values (e.g., always 19 values), you can use an array. If you have a varying number of values use a list. I will be using a list because this is a more universal approach.
var m = new List<double> {
200, 1000, 1500, 2000, 4000, 7000, 10000, 12000, 14000, 16000, 0, 0, 0, 0
};
Now you can use LINQ to process the values
double maximumValue = m
.Where(x => x != 0)
.Max();
The Where
extension method filters the values. x =>
introduces a variable to which each value will be assigned in turn. x != 0
is the condition which will applied to each of these values. Only the ones where the condition is fulfilled pass through the filter and are given over to the next stage, which is the Max
extension method returning the maximum value.
Note that the filter will only have an effect if you have only negative values and zeroes resulting in a negative maximum value. Because if the maximum is positive, the zeroes will not affect the result.
If you know that the maximum value will be a positive value, then you can simply write
double maximumValue = m.Max();