Avatar of ksd123
ksd123
 asked on

Looping in Dictionary using c#

Hi Experts,

I have a dictionary with key,value  both int values (dictionary<int>,<int>) about 20 items and want to find if a given input falls within the range of key and value of dictionary.

Ex:

dictionary items   =    [100,150],
                                    [200,225],
                                    [500,599] etc

If user enters 150, since the 120 exist within the first item range ,I should return true and exit the loop
If user enters 160, since the 160 does not exist on  any dictionary item' s range ,I should return false and exit the loop
If user enters 510 since the 510 exist within the third item range ,I should return true and exit the loop

I want to accomplish above task using c#
C#.NET ProgrammingASP.NET

Avatar of undefined
Last Comment
Fernando Soto

8/22/2022 - Mon
AndyAinscow

Why do you need a dictionary?  (This is making things rather difficult for you.  A dictionary is really good for rapid lookup of a random item.)
ASKER CERTIFIED SOLUTION
it_saige

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Fernando Soto

Hi ksd123;

Maybe you could use a collection of Tuple object as shown in the following code snippet.

// In place of using a Dictionary object to hold the data use a 
// list of tuple's and define it like this.
List<Tuple<int, int>> items = new List<Tuple<int, int>>();
// Populate the data as Tuple objects
items.Add(Tuple.Create( 100, 150 ));
items.Add(Tuple.Create( 200, 225 ));
items.Add(Tuple.Create( 500, 599 ));

// Test Data from the user
int userInput = 160;

// The variable result will be true or false after going through the collection
bool result = items.Any( i => userInput >= i.Item1 && userInput <= i.Item2 );

Open in new window

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck