Update in one Concurrentdictionary is reflected in main dictionary - c#

I have two concurrent dictionaries say
var MainDic = new ConcurrentDictionary<string, string>();
and
var TempDic = new ConcurrentDictionary<string, string>(MainDic);
My TempDic contains same data as MainDic.I do computations on TempDic. whatever changes are made to TempDic is reflected in MainDic. How do i stop this ,i need to keep MainDic as it is for further reference
Following is my actual code:
ConcurrentDictionary NetPositionData = new ConcurrentDictionary(); // Main 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;
}
here if flag is A i return data as it is else i call GetDayPosition. In GetDayPosition function whatever update i make in _DayPos is reflected in NetPositionData dictionary as well. because of this i lose my original data. I don't want this to happen

Are you sure about that?
var mainDic = new ConcurrentDictionary<string, string>();
mainDic["1"] = "foo";
var tempDic = new ConcurrentDictionary<string, string>(mainDic);
tempDic["1"] = "bar";
Console.Out.WriteLine(mainDic["1"]);
outputs -> foo

Related

How to use lastEvaluatedKey with .ScanAsync?

I want to paginate through records in a dynamo table using a lastEvaluatedKey. How can I use the scanfilter to use the lastEvaluatedKey to begin the next request at that given location?
public List<Record>? GetRecords(Request request)
{
// Define marker variable
Dictionary<string, AttributeValue> startKey = null!;
var records = new List<Record>();
do
{
// Issue request
Condition cond = new Condition();
cond.ComparisonOperator = "NULL";
cond.AttributeValueList = new List<AttributeValue>() { };
var scanFilter = new Dictionary<string, Condition>() { { "ExecutedTime", cond } };
var allEvents = client.ScanAsync("rRecords", scanFilter).Result; //Dictionary<string, Condition> scanFilter
// View all returned items
List<Dictionary<string, AttributeValue>> items = allEvents.Items;
foreach (Dictionary<string, AttributeValue> item in items)
{
//do stuff
}
// Set marker variable
startKey = allEvents.LastEvaluatedKey;
} while (startKey != null && startKey.Count != 0);
return scheduledEventRecords;
}
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetScanning.html I have tried this approach but those APIs (.Scan on the AmazonDynamoDBClient) are not available the version AWSSDK 3.5.1.20 that I am currently using.

How to select a dictionary which is in a List<Task<Dictionary>>> to display on listbox

I have to display a list of words from my dictionary into a list box.
I had to use tasks since I needed to use async for the assignment.
private void button3_Click(object sender, EventArgs e)
{
files.Add(filePath);
files.Add(filePath2);
List<Task<Dictionary<string, int>>> tasks = new List<Task<Dictionary<string, int>>>();
foreach (var file in files)
{
tasks.Add(wordreaderasync(file));
}
Task.WaitAll(tasks.ToArray());
listBox1.DataSource = tasks[0];
listBox1.DisplayMember = "Value";
listBox1.DisplayMember = "Key";
}
public async Task<Dictionary<string, int>> wordreaderasync(string filename)
{
var lines = await File.ReadAllLinesAsync(filename);
var arrayfilter1 = lines.AsParallel().Where(x => x != string.Empty).Select(x => x.ToLower().Trim().Replace(",", "").Replace("'", ""));
var arrayfilter2 = arrayfilter1.SelectMany(x => x.Split(" "));
Dictionary<string, int> wordDictionary = new Dictionary<string, int>();
arrayfilter2.ToList().ForEach(x =>
{
if (wordDictionary.ContainsKey(x))
{
wordDictionary[x] += 1;
}
else
{
wordDictionary.Add(x, 1);
}
});
return wordDictionary;
}
I basically want to load the wordDictionary to my listbox. I do not understand how to exreact it from the list.

Compare two lists of same type

I need to compare two lists of same type. Assume I have CurrentSC List(Current modified data by user) and PreviousSC List(Saved data from database) of below class.
public class SoftClose
{
private int AID = -1;
private bool _softCloseInd;
private bool _softCloseEditInd;
private string _softClosedBy;
private DateTime _softClosedDate;
private ReferenceEnums.ActionStatus _status = ReferenceEnums.ActionStatus.NO_CHANGE;
}
public static void TPostProcessAddRemoveSoftCloseStopPaymentPrefixes(IFPMServiceInternal fpmService, AgreementRevision revision)
{
List<SoftClose> psc = null;
List<SoftClose> csc = null;
string fanValue = revision.Agreement.FAN;
psc = fpmService.GetSoftCloseByFAN(fanValue);
if (psc != null)
{
//var currentprefixes = revision.Details.Where(x => x.Prefix != null).Select(y => y.Prefix).Distinct();
//Create current SoftClose object using revision object
foreach (var prefix in revision.Details.Where(x => x.Prefix != null).Select(y => y.Prefix).Distinct())
{
var newSF =
new SoftClose
{
Id = -1,
Status = ReferenceEnums.ActionStatus.NO_CHANGE,
AgreementRevId = revision.Id,
AgreementId = revision.Agreement.Id,
WorkflowStatus = revision.WorkflowStatus,
FAN = revision.Agreement.FAN,
PID = (int)revision.Agreement.PID,
Prefix = prefix
};
csc.Add(newSF);
}
//Now you have previous and current softcloses to compare prefixes...
psc.OrderBy(x => x.Prefix.Id);
csc.OrderBy(x => x.Prefix.Id);
for(int i = 0; i < csc.Count; i++)
{
}
}
}
Lets say I have changed D3 value in PreviousSC to D2 in CurrentSC. Now i need to delete D3 value from database(As D2 value already there in database i don't need to insert) and chnage _status to DELETE and I added D4 value in CurrentSC which is not there is PreviousSC. Now I need to add D4 value in database and assign _softCloseInd and _softCloseEditInd to Y and change _status to ADD.
How to achieve this in best way?
class Program
{
static void Main(string[] args)
{
List<SoftClose> psc = new List<SoftClose>(){
new SoftClose(){ID=1, Status = "NO_CHANGE",AID=19, Prefix = "D1"},
new SoftClose(){ID=2, Status = "NO_CHANGE",AID=20, Prefix = "D2"},
new SoftClose(){ID=3, Status = "NO_CHANGE",AID=21, Prefix = "D3"},
new SoftClose(){ID=3, Status = "NO_CHANGE",AID=22, Prefix = "D9"}
};
List<SoftClose> csc = new List<SoftClose>(){
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=19, Prefix = "D2"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=20, Prefix = "D2"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=21, Prefix = "D6"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=22, Prefix = "D4"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=23, Prefix = "D5"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=24, Prefix = "D3"}
};
List<SoftClose> esc = new List<SoftClose>();
Console.WriteLine("---------Previous List----------");
foreach (var item in psc)
{
Console.WriteLine($"Id:{item.ID}, Desc1:{item.Prefix}, Status:{item.Status}");
}
Console.WriteLine("--------------------------------------");
Console.WriteLine("---------Current List----------");
foreach (var item in csc)
{
Console.WriteLine($"Id:{item.ID}, Desc1:{item.Prefix}, Status:{item.Status}");
}
Console.WriteLine("--------------------------------------");
var addlist = csc.Where(c => psc.All(p => !p.Prefix.Equals(c.Prefix)));
foreach (var n in addlist)
{
var index = csc.FindIndex(p => p.Prefix.Equals(n.Prefix));
csc[index].Status = "ADD";
esc.Add(csc[index]);
}
var deletelist = psc.Where(p => p.Status.Equals("NO_CHANGE") && !csc.Exists(c => c.Prefix.Equals(p.Prefix)));
foreach (var n in deletelist)
{
var index = psc.FindIndex(c => c.Prefix.Equals(n.Prefix));
if (psc.FindIndex(c => c.Prefix.Equals(n.Prefix)) >= 0)
{
psc[index].Status = "REMOVE";
esc.Add(psc[index]);
}
}
Console.WriteLine("---------Effective List----------");
foreach (var item in esc)
{
Console.WriteLine($"Id:{item.ID}, Prefix:{item.Prefix}, Status:{item.Status}");
}
Console.ReadLine();
}
}
public class SoftClose
{
public int ID = -1;
public int AID = -1;
public int WFID = -1;
public string Prefix;
public DateTime SCDATE;
public string Status;
}

Get Json Object From QueryString c#

The best I found was that available solutions at stack do not have answer for nested json object, they only address liner json values. But I have data to send is like
{ ob: { a: "78", b: { a: "gffg", h: {m:67, j:"fff"} } } }
If I want to do it in php i would just do
$json = $_POST['ob'];
$obj = json_decode($json);
But In c# I can'not do that. So I would appreciate any built-in method if available and I would love to be helped to fix my following code
I want to make a nested dictionary (I would prefer JOBject though). For ease of showing output I have serialized the result,
What result I have achieved yet from following code is
{"a":"78","ob":{},"ob.b":{"a":"gffg"},"ob.b.h":{"m":"67","j":"fff"}} but desired result is like sent data { "ob": { "a": "78", "b": { "a": "gffg", "h": {m:67, "j":"fff"} } } } Code is
string getJsonStringFromQueryString()
{
Dictionary<string, object> dic = new Dictionary<string, object>();
var nvc = Request.QueryString;
foreach (string key in nvc.Keys)
{
string[] values = nvc.GetValues(key);
string tempKey = key;
tempKey = tempKey.Replace("[", ".").Replace("]", "");
if (values.Length == 1)
dic.Add(tempKey, values[0]);
else
dic.Add(tempKey, values);
}
//It is giving me
{[ob.a, 78]}
{[ob.b.a, gffg]}
{[ob.b.h.m, 67]}
{[ob.b.h.j, fff]}
var result = makeNestedObject(dic);
var json = new JavaScriptSerializer().Serialize(result);
return json;
}
I am trying to add the leaf keys and their values as it is and all other keys as dictionary
Dictionary<string, object> makeNestedObject(Dictionary<string, object> qsDictionar)
{
Dictionary<string, object> result = new Dictionary<string, object>();
foreach (string key in qsDictionar.Keys)
{
string temp = "";
if (key.Contains("."))
{
string[] ar = key.Split('.');
if (ar.Length > 2)
{
for (int i = 0; i < ar.Length - 1; i++)
{
temp = ar[0];
for (int j = 1; j <= i; j++)
{
temp += "." + ar[j];
}
//above is getting the previous key i want to use as dictionary, leaving the leaf key.
try
{
Dictionary<string, object> forTry = (Dictionary<string, object>)result[temp];
}
catch
{
result.Add(temp, new Dictionary<string, object>());
}
}
((Dictionary<string, object>)result[temp]).Add(ar[ar.Length - 1], qsDictionar[key]);
}
else
result.Add(ar[1], qsDictionar[key]);
}
}
return result;
}
Following method gives you complete solution for any json object.
string getJsonStringFromQueryString()
{
Dictionary<string, object> dic = new Dictionary<string, object>();
var nvc = Request.QueryString;
foreach (string key in nvc.Keys)
{
string[] values = nvc.GetValues(key);
string tempKey = key;
tempKey = tempKey.Replace("[", ".").Replace("]", "");
if (values.Length == 1)
dic.Add(tempKey, values[0]);
else
dic.Add(tempKey, values);
}
string vald = Request.QueryString["ob"];
var result = makeNestedObject(dic);
var json = new JavaScriptSerializer().Serialize(result);
return json;
}
Dictionary<string, object> makeNestedObject(Dictionary<string, object> qsDictionar)
{
Dictionary<string, object> result = new Dictionary<string, object>();
foreach (string key in qsDictionar.Keys)
{
if (key.Contains("."))
{
List<string> keysList = key.Split('.').ToList();
Dictionary<string, object> lastAddedDictionary = result;
while (keysList.Count > 1)
{
if (!lastAddedDictionary.ContainsKey(keysList[0]))
{
Dictionary<string, object> temp = new Dictionary<string, object>();
lastAddedDictionary[keysList[0]] = temp;
lastAddedDictionary = temp;
}
else
lastAddedDictionary = (Dictionary<string, object>)lastAddedDictionary[keysList[0]];
keysList.RemoveAt(0);
}
lastAddedDictionary[keysList[0]] = qsDictionar[key];
}
else
{
result.Add(key, qsDictionar[key]);
}
}
return result;
}

Confused about how get value from DictionaryList at specific index

I am using a DictionaryList to keep some values coming from an xml file
this is the my xml file
<DnsServers>
<Dns>
<Name>Google</Name>
<Value>8.8.8.8,8.8.4.4</Value>
</Dns>
<Dns>
<Name>Telekom</Name>
<Value>195.175.39.39,195.175.39.40</Value>
</Dns>
</DnsServers>
and then populating a combobax just key values like this way .
void ReadFromDnsServerList()
{
_nameValueDictionary = new Dictionary<string, string>();
//var list = new List<string>();
XDocument doc = XDocument.Load("DnsServerList.xml");
if (doc.Root != null)
{
var keyValueXml = from c in doc.Root.Descendants("Dns")
select new
{
name = c.Element("Name").Value,
value = c.Element("Value").Value
};
foreach (var info in keyValueXml)
{
_nameValueDictionary.Add(info.name,info.value);
}
foreach (KeyValuePair<string, string> item in _nameValueDictionary)
{
cmbDns.Items.Add(item.Key);
}
}
}
I am wondering that How can I get corresponding dns value inside cmbDns_SelectedIndexChanged
change event somethinglike this
name=Google value =8.8.8.8,8.8.4.4
Try this:
void ReadFromDnsServerList()
{
_nameValueDictionary = new Dictionary<string, string>();
XDocument doc = XDocument.Load("DnsServerList.xml");
if (doc.Root != null)
{
var keyValueXml = from c in doc.Root.Descendants("Dns")
select new
{
name = c.Element("Name").Value,
value = c.Element("Value").Value
};
foreach (var info in keyValueXml)
{
_nameValueDictionary.Add(info.name, info.value);
}
cmbDns.DisplayMember = "Key";
cmbDns.ValueMember = "Value";
cmbDns.DataSource = _nameValueDictionary.ToArray();
}
}
I hope it helps.

Categories

Resources