Link to home
Start Free TrialLog in
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#
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

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
Avatar of it_saige
it_saige
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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