c# - Compare value with array and get closest value to it -


i'm rookie in c# , i'm trying learn language.

can guys give me tip how can compare array value picking lowest it?

like:

double[] w = { 1000, 2000, 3000, 4000, 5000 };  double min = double.maxvalue; double max = double.minvalue;  foreach (double value in w) {     if (value < min)         min = value;     if (value > max)         max = value; }  console.writeline(" min:", min);  

gives me lowest value of w, how can compare now?

if have:

int p = 1001 + 2000;  // 3001 

how can compare list of array , find out (3000) value nearest value "searchvalue"?

you can simple mathematics , there different approaches.

linq

double searchvalue = ...;  double nearest = w.select(p => new { value = p, difference = math.abs(p - searchvalue) })                   .orderby(p => p.difference)                   .first().value; 

manually

double[] w = { 1000, 2000, 3000, 4000, 5000 };  double searchvalue = 3001; double currentnearest = w[0]; double currentdifference = math.abs(currentnearest - searchvalue);  (int = 1; < w.length; i++) {     double diff = math.abs(w[i] - searchvalue);     if (diff < currentdifference)     {         currentdifference = diff;         currentnearest = w[i];     } } 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -