4
\$\begingroup\$

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[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].Key

etc.

\$\endgroup\$
9
\$\begingroup\$

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.

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

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.

\$\endgroup\$
  • \$\begingroup\$ that looks a lot cleaner than what I was going to do. \$\endgroup\$ – Malachi Nov 22 '13 at 16:08
  • 2
    \$\begingroup\$ 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.) \$\endgroup\$ – svick Nov 22 '13 at 16:10
  • \$\begingroup\$ @svick good spot, changed to IEnumerable<KeyValuePair<K, V>>. \$\endgroup\$ – MattDavey Nov 22 '13 at 16:18
  • \$\begingroup\$ Though your answer is good I was looking for something like what svick did. Thanks anyway ! \$\endgroup\$ – WizLiz Nov 22 '13 at 19:04
  • 1
    \$\begingroup\$ 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) \$\endgroup\$ – Sedat Kapanoglu Nov 22 '13 at 22:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.