I cant wrap my head around this problem.
I have two dictionaries with the same keys. However the second dictionary is mixed up and the keys are in a different order. I want to be able to calculate how far each key in the new dictionary is away from its original position in the first dictionary.
Eg: Key 1 was moved to key 3 (in the second dictionary) so the disorder would be 2
As far as I know there is no built-in method to do this.But you can use this method to get index differences between two dictionary items (by keys).
public static int GetIndexDifference(IDictionary source, IDictionary target, object key)
{
int index1=0, index2=0;
int currentPosition = 1;
foreach (var element in source.Keys)
{
if (element.Equals(key))
{
index1 = currentPosition;
break;
}
currentPosition++;
}
currentPosition = 1;
foreach (var element in target.Keys)
{
if (element.Equals(key))
{
index2 = currentPosition;
break;
}
currentPosition++;
}
return Math.Abs(index1 - index2);
}
You can use it like this:
var dict1 = new Dictionary<string, string> {{"sample1", "some item"}, {"sample2", "some item"}};
var dict2 = new Dictionary<string, string> { { "sample2", "some item" },{ "sample1", "some item" }, };
Console.WriteLine(GetIndexDifference(dict1,dict2,"sample1"));
Or you can use it with LINQ:
var disOrders = dict1.Select(item => GetIndexDifference(dict1, dict2, item.Key)).ToList();
It will give you all disOrders count as a List<int>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.