簡體   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