Outer and inner loops with dictionary

genush 1 Reputation point
2021-12-21T14:48:21.647+00:00

I have a dictionary and I want to compare its elements. I've looped over dictionaries using foreach and KeyValuePair but what I need is the outer loop to tsrat with the first key and end at the second-to-last key, then the inner loop to start at the next key of the outer loop current index and end at the last key. If I had an array of length n, I would do something like:

for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)

Is there a way to do this with a Dictionary and its keys?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,277 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,686 Reputation points
    2021-12-21T15:53:45.58+00:00

    just convert the dictionary to an array of KeyValuePairs:

    var a = dict.ToArray();

    0 comments No comments

  2. Karen Payne MVP 35,036 Reputation points
    2021-12-21T16:19:25.767+00:00

    If you are comparing two Dictionaries try this done in .NET Core 5, C# 9

    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Dictionary<int, string> dict1 = new()
                {
                    [0] = "Vince",
                    [1] = "James",
                    [2] = "Anne"
                };
                Dictionary<int, string> dict2 = new()
                {
                    [0] = "Vince",
                    [1] = "Mary",
                    [2] = "Anne",
                    [3] = "Sam"
                };
    
                // note the check for contains key as the two dictionaries are different lengths
                Dictionary<int, string> results = dict2.Where(entry 
                        => dict1.ContainsKey(entry.Key) && dict1[entry.Key] != entry.Value)
                    .ToDictionary(entry => entry.Key, entry => entry.Value);
    
                foreach (var kvp in results)
                {
                    Debug.WriteLine($"{kvp.Key} - {kvp.Value}");
                }
    
            }
        }
    }
    
    0 comments No comments