1

I have an output of a method that provides two key pieces of data per result. Eg: 20160503 and nzdusd.

How can I store this in a dictionary and the sort against either one? I want to be able to sort against key or value but can't get past adding the data! Is there another data structure better suited?

Previously I tried simply calling Add()

But got an ArgumentException with message, An item with the same key has already been added..

Dictionary<string, string> missingDays = new Dictionary<string, string>();

// Some logic
missingDays.Add(formattedDate, fxPair); // Exception here

foreach (var missingDay in missingDays)
                {
                    Console.WriteLine(missingDay);
                }

1 Answer 1

3

A dictionary must have unique key values. In this case the formattedDate variable is being assigned the same value more than once, which causes an exception the second time you try to add an entry to the dictionary with the same formattedDate value.

You can use a Tuple<string, string> inside a list (List<Tuple<string, string>>) to store the values, and then use the LINQ method OrderBy() to sort the list.

var missingDays = new List<Tuple<string, string>>();

missingDays.Add(Tuple.Create("exampleFormattedDate", "exampleFxPair"));

foreach (var missingDay in missingDays.OrderBy(md => md.Item1))
{
    Console.WriteLine(missingDay);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.