I have a Dictionary of Dictionaries that I need to traverse to find two records with various matching parameters. I have two foreach loops to do this which is O(n^2). I am looking for inspiration to find a better way of doing this by using the keys to improve lookup.
Simple example below.
edit: Each record contains many values that I would want to try and match. Below I'm looking for a BUY and a SELL transaction in the records. I would also want to maybe match for the same customer and same location, which are keys in the record dictionary. It is possible that the Dictionary only has "BUY" Transaction values. The record dictionary also contains different value types, like double and int.
- <"uniqueRecordIdABC", <"Transaction", "BUY">, <"Location", "Store1">, <"Client", "Bob">>
- <"uniqueRecordIdDEF", <"Transaction", "SELL">, <"Location", "Store2">, <"Client", "Bob">>
What I've thought about doing is making the uniqueRecordKey something that I could parse, improving the lookup. IE: 1:BUY:Store1:Bob, 2:SELL:Store2:Bob, but I'm not sure if there is any real benefit to that either.
Example:
Dictionary<string, Dictionary<string, object>> records
foreach (var item in records)
{
Dictionary<string, object> record = item.Value;
string transaction1 = Convert.ToString(record["Transaction"]);
string name1 = Convert.ToString(record["Client"]);
string location1 = Convert.ToString(record["Location"]);
foreach (var item2 in records)
{
Dictionary<string, object> record2 = item2.Value;
string transaction2 = Convert.ToString(record["Transaction"]);
string name2 = Convert.ToString(record["Client"]);
string location2 = Convert.ToString(record["Location"]);
if ((transaction1 == "BUY" && transaction2 == "SELL" || transaction1 == "SELL" && transaction2 == "BUY") && name1 == name2 && location1 == location2)
{
}
}
}