簡體   English   中英

均衡兩個字典的最快方法

[英]Fastest way to equalize two dictionaries

我有兩個排序字典。 第一個僅填充了NAN,第二個具有一些值。

我想將第一個的NAN更改為第二個的NAN。

SortedDictionary<double, float> newlogdict = newlog.Samples;
SortedDictionary<double, float> oldlogdict = oldlog.Samples;

foreach (KeyValuePair<double, float> kvp in newlogdict)
{
    oldlogdict[kvp.Key] = kvp.Value;
}

它可以工作,但是速度太慢,有沒有更快的方法?

這很慢,因為您的代碼增加了oldlogdict的大小(也許是它的兩倍)。 如果

oldlogdict[kvp.Key]

在未找到的位置,則您要添加帶有以下行的新元素

oldlogdict[kvp.Key] = kvp.Value;

我使用以下示例數據測試了您的代碼:

SortedDictionary<double, float> newlogdict = new SortedDictionary<double, float>();
SortedDictionary<double, float> oldlogdict = new SortedDictionary<double, float>();

float x1 = 3.5F;
double a = 3.3;

newlogdict.Add(double.NaN, x1);
oldlogdict.Add(a, x1);

foreach (KeyValuePair<double, float> kvp in newlogdict)
{
    oldlogdict[kvp.Key] = kvp.Value;      //if key is not found it will be added
}

Console.WriteLine(newlogdict.Count);
Console.WriteLine(oldlogdict.Count);

另請注意,在SortedDictionaryKeyNotFoundException僅在Get期間拋出,而不是MSDN上記錄的Set

這是簡明或合並,在這里提到

似乎沒有更快的方法,但是代碼更短

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM