patterncsharpModerate
Writing information from a List of KeyValuePairs into a DataRow
Viewed 0 times
datarowintowritingkeyvaluepairslistfrominformation
Problem
I have the following algorithm which retrieves information in a
The ouput is a
etc.
List of KeyValuePair (prices) and write them in a DataRow. I was wondering if I could achieve the same result without j. if (prices != null)
{
for (int i = 8, j=0; j < prices.Count; i+=2, j++)
{
res[i] = prices[j].Value;
res[i+1] = prices[j].Key;
}
}The ouput is a
DataRow as follow :res[8] = prices[0].Value
res[9] = prices[0].Key
res[10] = prices[1].Value
res[11] = prices[1].Key
res[12] = prices[2].Value
res[13] = prices[2].Keyetc.
Solution
I would approach this first by flattening the prices dictionary into a sequence of values eg
Using this I can simply loop over the flattened dictionary and copy the values into the data row:
I suspect there is a far better term than "flatten" for what I'm doing with the dictionary here.
{ Key, Value, Key, Value, Key, Value }.// This method is returning object for now since I'm not clear what types are in your data row..
IEnumerable Flatten(IEnumerable> pairs)
{
foreach (var pair in pairs)
{
yield return pair.Value;
yield return pair.Key;
}
}Using this I can simply loop over the flattened dictionary and copy the values into the data row:
int offset = 8;
foreach (var x in Flatten(prices))
{
res[offset++] = x;
}I suspect there is a far better term than "flatten" for what I'm doing with the dictionary here.
Code Snippets
// This method is returning object for now since I'm not clear what types are in your data row..
IEnumerable<object> Flatten<K, V>(IEnumerable<KeyValuePair<K, V>> pairs)
{
foreach (var pair in pairs)
{
yield return pair.Value;
yield return pair.Key;
}
}int offset = 8;
foreach (var x in Flatten(prices))
{
res[offset++] = x;
}Context
StackExchange Code Review Q#35924, answer score: 12
Revisions (0)
No revisions yet.