just convert the dictionary to an array of KeyValuePairs:
var a = dict.ToArray();
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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?
just convert the dictionary to an array of KeyValuePairs:
var a = dict.ToArray();
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}");
}
}
}
}