{"id":1567,"date":"2017-09-20T14:21:31","date_gmt":"2017-09-20T14:21:31","guid":{"rendered":"https:\/\/puvox.software\/?p=1567"},"modified":"2021-11-14T13:45:49","modified_gmt":"2021-11-14T13:45:49","slug":"find-several-nearest-to-x-values-in-c-dictionarylistarray","status":"publish","type":"post","link":"https:\/\/puvox.software\/blog\/find-several-nearest-to-x-values-in-c-dictionarylistarray\/","title":{"rendered":"Find several nearest (closest) values in C# Dictionary\/List\/Array"},"content":{"rendered":"<div class=\"default-content-clss content_1567 type_post \"><p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-1569 size-full\" src=\"https:\/\/puvox.software\/wp-content\/uploads\/2017\/09\/values-pairs.png\" alt=\"keys and value in an array or dictionary\" width=\"504\" height=\"152\" srcset=\"https:\/\/puvox.software\/blog\/wp-content\/uploads\/sites\/2\/2017\/09\/values-pairs.png 504w, https:\/\/puvox.software\/blog\/wp-content\/uploads\/sites\/2\/2017\/09\/values-pairs-300x90.png 300w, https:\/\/puvox.software\/blog\/wp-content\/uploads\/sites\/2\/2017\/09\/values-pairs-400x121.png 400w, https:\/\/puvox.software\/blog\/wp-content\/uploads\/sites\/2\/2017\/09\/values-pairs-60x18.png 60w, https:\/\/puvox.software\/blog\/wp-content\/uploads\/sites\/2\/2017\/09\/values-pairs-500x152.png 500w\" sizes=\"(max-width: 504px) 100vw, 504px\" \/><\/p>\n<h1 style=\"text-align: center;\">Find several nearest numbers in C# Dictionary<\/h1>\n<p>Recently I had a small task, trying to solve a specific problem. Maybe there exist better methods to solve the problem, though\u00a0as I am new to C#, I&#8217;ve tried to solve it with &#8220;primitive&#8221; method.<\/p>\n<p>I had a dictionary (it will be somehow similar with List or Array), which had keys\/pairs like this:<\/p>\n<pre>[0] =&gt; 13\r\n[1] =&gt; 18\r\n[2] =&gt; 24\r\n[3] =&gt; 35\r\n[4] =&gt; 42\r\n[5] =&gt; 54\r\n[6] =&gt; 66\r\n[7] =&gt; 74<\/pre>\n<p style=\"text-align: right;\"><span style=\"font-size: 8pt;\"><em>(this dictionary was being sorted either in Ascending or Descending)<\/em><\/span><\/p>\n<p>Then the program was provided with a random number (by provider), let&#8217;s say number <span style=\"color: #ff0000; font-size: 18pt;\"><strong>21<\/strong> <\/span>and the program had\u00a0to find nearest\u00a0<span style=\"color: #ff0000;\"><strong><span style=\"font-size: 18pt;\">2<\/span><\/strong><span style=\"color: #000000;\"> greater\u00a0values and <span style=\"font-size: 18pt; color: #ff0000;\"><strong>2<\/strong><\/span>\u00a0less\u00a0values \u00a0&#8211; in this case answer should be: <strong>13,18(below)<\/strong> and <strong>24,35(above)<\/strong>.<\/span><\/span><\/p>\n<p>However, for them, who want to do a quick home-task and dont want to rewrite from ground, this snippet might be useful (I think the code is self-explaining). At first, I determined if dictionary is ascending or descending, then manually counted every &#8220;greater&#8221; and &#8220;less&#8221; occurrences and removed all other keys :<\/p>\n<pre>Dictionary&lt;int,double&gt; MyD = Dictionary&lt;int,double&gt;();\r\n    MyD[0] = 13;\r\n    MyD[1] = 18;\r\n    MyD[2] = 24;\r\n    MyD[3] = 35;\r\n    MyD[4] = 42;\r\n    MyD[5] = 54;\r\n    MyD[6] = 66;\r\n    MyD[7] = 74;\r\n    \r\ndouble Target_value = 21;\r\nint how_many_values_to_find = 2;\r\n\r\nDictionary&lt;int,double&gt; MyD_New =FindNearestValuesInDict(MyD, Target_value,how_many_values_to_find);   \/\/ =====&gt;  returns 13,18 and 24,35\r\n\r\n<\/pre>\n<p>Actual code of method is:<\/p>\n<pre>\/\/ ============================== find nearest values ================== \/\/\r\npublic  Dictionary&lt;int, double&gt; FindNearestValuesInDict(Dictionary&lt;int,double&gt; MyDict, double Target_value, int how_many_values_to_find){\t\t\t\r\n\tbool Is_Ascending= DictIsAscendingOrDescending(MyDict);\r\n\tint KeysAmount= MyDict.Keys.Count(); \t\t\r\n\tint greater_count=0, lower_count=0;\r\n\tint idx_pos=0, idx_neg=0; \r\n\tDictionary &lt;int, double&gt; MyDictFinal= new Dictionary&lt;int,double&gt;(MyDict);\r\n\r\n\tfor(int i=0; i &lt; KeysAmount; i++){ \r\n\t\tidx_pos = Is_Ascending ? i : KeysAmount-1-i; \r\n\t\tidx_neg = Is_Ascending ? KeysAmount-1-i : i;  \r\n\t\t\/\/remove all \"grater than\" occurences\r\n\t\tif(MyDict.Keys.ElementAtOrDefault(idx_pos) != null){\r\n\t\t\tdynamic keyNm_pos= MyDict.Keys.ElementAt(idx_pos); \r\n\t\t\tif(ContainsValue(MyDict,keyNm_pos)) { \r\n\t\t\t\tif (MyDict[keyNm_pos] &gt; Target_value) {   \r\n\t\t\t\t\tgreater_count ++;  \r\n\t\t\t\t\tif( greater_count &gt;how_many_values_to_find) { \r\n\t\t\t\t\t\tMyDictFinal.Remove(keyNm_pos); \r\n\t\t\t\t\t}   \r\n\t\t\t\t}\r\n\t\t\t} \r\n\t\t}\r\n\t\t\r\n\t\t\/\/remove all \"lower than\" occurences\r\n\t\tif(MyDict.Keys.ElementAtOrDefault(idx_neg) != null){\r\n\t\t\tdynamic keyNm_neg= MyDict.Keys.ElementAt(idx_neg); \r\n\t\t\tif(ContainsValue(MyDict,keyNm_neg)) { \r\n\t\t\t\tif (MyDict[keyNm_neg] &lt; Target_value) { \r\n\t\t\t\t\tlower_count++;   \r\n\t\t\t\t\tif( lower_count&gt;how_many_values_to_find) { \r\n\t\t\t\t\t\tMyDictFinal.Remove(keyNm_neg); \r\n\t\t\t\t\t}  \r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn MyDictFinal;\r\n}\r\n\/\/ helper function to above\r\npublic bool DictIsAscendingOrDescending(Dictionary&lt;int,double&gt; MyDict){\r\n\t\/\/ Note: some keys might not exist at all \/\/\r\n\tint KeysAmount= MyDict.Keys.Count(); \r\n\tdouble last_obtained_value=double.NaN; \r\n\t\/\/find if ascending or descending\r\n\tfor(int i=0; i&lt; KeysAmount; i++){ \t\r\n\t\tdynamic keyNm= MyDict.Keys.ElementAt(i);\r\n\t\tif(ContainsValue(MyDict,keyNm)) { \r\n\t\t\tif (!double.IsNaN(last_obtained_value)){\r\n\t\t\t\t return MyDict[keyNm]&gt;last_obtained_value;\r\n\t\t\t}\r\n\t\t\tlast_obtained_value = MyDict[keyNm];\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\/\/ ============================================================================ \/\/<\/pre>\n<\/div>","protected":false},"excerpt":{"rendered":"<div class=\"default-content-clss excerpt_1567 type_post \"><p>Find several nearest numbers in C# Dictionary Recently I had a small task, trying to solve a specific problem. Maybe there exist better methods to solve the problem, though\u00a0as I<a class=\"excerpt-read-more\" href=\"https:\/\/puvox.software\/blog\/find-several-nearest-to-x-values-in-c-dictionarylistarray\/\">(Continue Reading)<\/a><\/p>\n<\/div>","protected":false},"author":1,"featured_media":1569,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[17],"tags":[],"class_list":["post-1567","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-coding"],"_links":{"self":[{"href":"https:\/\/puvox.software\/blog\/wp-json\/wp\/v2\/posts\/1567","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/puvox.software\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/puvox.software\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/puvox.software\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/puvox.software\/blog\/wp-json\/wp\/v2\/comments?post=1567"}],"version-history":[{"count":0,"href":"https:\/\/puvox.software\/blog\/wp-json\/wp\/v2\/posts\/1567\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/puvox.software\/blog\/wp-json\/wp\/v2\/media\/1569"}],"wp:attachment":[{"href":"https:\/\/puvox.software\/blog\/wp-json\/wp\/v2\/media?parent=1567"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/puvox.software\/blog\/wp-json\/wp\/v2\/categories?post=1567"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/puvox.software\/blog\/wp-json\/wp\/v2\/tags?post=1567"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}