I have a case like, I have to fetch the non zero values of an array, sort them and find the median of values. I did as follows,
var array2 = (from t in array1 where t.array2 != 0 select t.array2).ToArray();
Array.Sort(array2);
var Median = array2.Length % 2 == 0 ? new List<double>() { ((array2[array2.Length / 2 - 1]) + (array2[array2.Length / 2])) / 2 } : new List<double>() { array2[array2.Length / 2] };
For now all going fine. But I am thinking of merging the first two lines in a single one like, copying the non zero values using orderby method. For this I have tried like,
var array2 = (from t in ipedsTableValue where t.array2 != 0 select t.array2).ToArray(t); // Not worked
Also suggest me if there are any super way to calculate median of an array in C# because that line is also looking so big and I am afraid that is not easily readable.
I have referred SO resource: Add a Median Method to a List Though it is working fine, I am thinking of some simple and efficient code with some less number of codes. Any suggestion would be helpful!
Try like this
var array2= (from t in array1 where t.array2!= 0 select t.array2).OrderBy(t => t).ToArray();