Storing duplicate key value pairs in C#

Viewed 31671

I have a data like in (string , int) pair. How to store this data in collection object. Both values can be duplicate. Which collection object should i use??

EDIT: How can i access elements separately..??

4 Answers

You can use List<KeyValuePair<string,int>>.

This will store a list of KeyValuePair's that can be duplicate.

You can use List<KeyValuePair<string, int>> if you want to add & remove items, or KeyValuePair<string, int>[] if the number of items is known

If you want to avoid repeating the key for multiple values you can use Dictionary<string, List<int>>.

        List<KeyValuePair<int, int>> list = new List<KeyValuePair<int, int>>();

        for (int i = 0; i < 30; i++)
        {
            int x = new Random().Next(2, 50);
            int y = new Random().Next(2, 5000);

            Console.WriteLine("In ==> Key: " + x+"\tValue: "+y);
            list.Add(new KeyValuePair<int, int>(x, y));
        }

        //before sorting, a list uses FIFO (1st In, 1st Out) order
        //LI.Sort();//NOTE: Only sorts simple data types.
        //LI.Reverse();//NOTE: Only Reverses simple data types.
        foreach (var x in list.FindAll(m => m.Value > 3500))//simple lambda expression to filter out the list contents (KeyValuePair)
        {
            Console.WriteLine("Key: " + x.Key + "\tValue: " + x.Value);
        }
        Console.ReadLine();
Related