我有两个并发词典
var MainDic = new ConcurrentDictionary<string, string>();
和
var TempDic = new ConcurrentDictionary<string, string>(MainDic);
我的TempDic
包含与MainDic
相同的数据。我在TempDic
上进行了计算。对TempDic
所做的任何更改都会反映在MainDic
中。我如何阻止这一点,我需要保留MainDic
,以便进一步参考
以下是我的实际代码:
ConcurrentDictionary NetPositionData = new ConcurrentDictionary(); //主要Dic
private DataView GetNetPositionData()
{
this.NetPosition.Tables[0].Rows.Clear();
DataView view = new DataView();
ConcurrentDictionary<string, DataNetPosition> Postion;
if (NetPosFlag == "A")
{
foreach (KeyValuePair<string, DataNetPosition> entry in NetPositionData)
{
this.NetPosition.Tables[0].Rows.Add(entry.Value.Exchange, entry.Value.SecurityId, entry.Value.ClientId, entry.Value.LTP);
}
}
else
{
Postion = new ConcurrentDictionary<string, DataNetPosition>(GetDayPosition(NetPositionData));
foreach (KeyValuePair<string, DataNetPosition> entry in Postion)
{
this.NetPosition.Tables[0].Rows.Add(entry.Value.Exchange, entry.Value.SecurityId, entry.Value.ClientId, entry.Value.LTP);
}
}
return view;
}
private ConcurrentDictionary<string, DataNetPosition> GetDayPosition(ConcurrentDictionary<string, DataNetPosition> _ALLPos)
{
var _DayPos = new ConcurrentDictionary<string, DataNetPosition>(_ALLPos);
try
{
DataView dv = new DataView(CFnetposition.Tables[0]);
for (int i = 0; i < dv.Table.Rows.Count; i++)
{
string NKey = dv.Table.Rows[i]["Exchange"].ToString() + dv.Table.Rows[i]["SecurityId"].ToString() + dv.Table.Rows[i]["ClientID"].ToString() + dv.Table.Rows[i]["Product"].ToString();
if (_DayPos.ContainsKey(NKey))
{
var dnp = _DayPos[NKey];
if (dv.Table.Rows[i]["Buy/Sell"].ToString() == "Buy")
{
dnp.BuyQuantity = dnp.BuyQuantity - Convert.ToDouble(dv.Table.Rows[i]["Quantity"]);
dnp.BuyVal = dnp.BuyVal - Convert.ToDouble(dv.Table.Rows[i]["TradeValue"]);
}
else
{
dnp.SellQuantity = dnp.SellQuantity - Convert.ToDouble(dv.Table.Rows[i]["Quantity"]);
dnp.SellVal = dnp.SellVal - Convert.ToDouble(dv.Table.Rows[i]["TradeValue"]);
}
dnp.BuyAvg = dnp.BuyQuantity == 0 ? 0 : dnp.BuyVal / dnp.BuyQuantity;
dnp.SellAvg = dnp.SellQuantity == 0 ? 0 : dnp.SellVal / dnp.SellQuantity;
dnp.NetQuantity = dnp.BuyQuantity - dnp.SellQuantity;
// other caluculations
_DayPos.TryUpdate(NKey, dnp, null);
}
}
}
catch (Exception ex)
{
}
return _DayPos;
}
这里如果flag是A我返回数据,因为它是我调用GetDayPosition。在GetDayPosition函数中,我在_DayPos中所做的任何更新都反映在NetPositionData字典中。因为这样我丢失了原始数据。我不希望这种情况发生
答案 0 :(得分:0)
你确定吗?
var mainDic = new ConcurrentDictionary<string, string>();
mainDic["1"] = "foo";
var tempDic = new ConcurrentDictionary<string, string>(mainDic);
tempDic["1"] = "bar";
Console.Out.WriteLine(mainDic["1"]);
输出 - &gt; FOO