繁体   English   中英

找出两个字典之间的混乱程度

[英]Finding the degree of disorder between two dictionaries

我无法解决这个问题。

我有两个具有相同键的字典。 但是,第二个词典混合在一起,键的顺序不同。 我希望能够计算新词典中的每个键距其在第一个词典中的原始位置的距离。

例如:键1已移至键3(在第二本词典中),因此无序将为2

据我所知,没有内置方法可以执行此操作,但是您可以使用此方法来获取两个字典项之间的索引差异(通过键)。

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);
}

您可以像这样使用它:

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"));

或者您可以将其与LINQ一起使用:

var disOrders =  dict1.Select(item => GetIndexDifference(dict1, dict2, item.Key)).ToList();

它将使您的所有疾病都计为List<int>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM