# Writing information from a List of KeyValuePairs into a DataRow

I have the following algorithm which retrieves information in a 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 = prices.Value
res = prices.Key
res = prices.Value
res = prices.Key
res = prices.Value
res = prices.Key


etc.

You can calculate i from j as 2*j + 8 (and 2*j + 9). That would change your code to:

for (int j = 0; j < prices.Count; j++)
{
res[2*j + 8] = prices[j].Value;
res[2*j + 9] = prices[j].Key;
}


Though I'm not sure whether this is actually better code than the original.

• Well at least this answer my question perfectly. I dont know how I missed that however. – WizLiz Nov 22 '13 at 19:04

I would approach this first by flattening the prices dictionary into a sequence of values eg { 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<object> Flatten<K, V>(IEnumerable<KeyValuePair<K, V>> 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.

• that looks a lot cleaner than what I was going to do. – Malachi Nov 22 '13 at 16:08
• The question says it's a list of key-value pairs, not a dictionary. (Though that will just mean that you would change the type of pairs.) – svick Nov 22 '13 at 16:10
• @svick good spot, changed to IEnumerable<KeyValuePair<K, V>>. – MattDavey Nov 22 '13 at 16:18
• Though your answer is good I was looking for something like what svick did. Thanks anyway ! – WizLiz Nov 22 '13 at 19:04
• That is probably faster than the accepted answer because there is no arithmetic overhead. (Note: you need to yield Value before Key to conform OP's situation) – Sedat Kapanoglu Nov 22 '13 at 22:10