MaddoScientisto
MaddoScientisto

Reputation: 189

How to quickly fill a Dictionary from an array?

I have an object which has many string variables and they are filled from an array, this seems really inefficient to me but it was the only way I could figure on a short notice, now that I have a little time I'd like to improve it by using a dictionary to store all the values.

This is what I have right now:

Product product = new Product();
                string[] row = productsList[i];

                product.row1 = row;

                product.PRODUCTID = row[0];
                product.PRODUCTCODE = row[1];
                product.PRODUCT = row[2];
                product.CLEAN_URL = row[3];
                product.WEIGHT = row[4];
                product.LIST_PRICE = row[5];
                product.DESCR = row[6];
                product.FULLDESCR = row[7];
                product.KEYWORDS = row[8];
                product.TITLE_TAG = row[9];
                product.META_KEYWORDS = row[10];
                product.META_DESCRIPTION = row[11];
                product.AVAIL = row[12];
                product.RATING = row[13];
                product.FORSALE = row[14];
                product.SHIPPING_FREIGHT = row[15];
                product.FREE_SHIPPING = row[16];
                product.DISCOUNT_AVAIL = row[17];
                product.MIN_AMOUNT = row[18];
                product.LENGTH = row[19];
                product.WIDTH = row[20];
                product.HEIGHT = row[21];
                product.LOW_AVAIL_LIMIT = row[22];
                product.FREE_TAX = row[23];
                product.CATEGORYID = row[24];
                product.CATEGORY = row[25];
                product.POS = row[26];
                product.MEMBERSHIP = row[27];
                product.PRICE = row[28];
                product.THUMBNAIL = row[29];
                product.IMAGE = row[30];
                product.TAXES = row[31];
                product.ADD_DATE = row[32];
                product.VIEWS_STATS = row[33];
                product.SALES_STATS = row[34];
                product.DEL_STATS = row[35];
                product.SMALL_ITEM = row[36];
                product.SEPARATE_BOX = row[37];
                product.ITEMS_PER_BOX = row[38];
                product.GENERATE_THUMBNAIL = row[39];
                product.RETURN_TIME = row[40];
                product.MANUFACTURERID = row[41];
                product.MANUFACTURER = row[42];

It's really long and time consuming, especially since I'll have to eventually read it back and I'm not really looking forward to doing that this way, furthermore the Products class is a mess of string variables.

Is there a quick and painless way to loop through the array and add them all to a Dictionary ?

Upvotes: 0

Views: 2173

Answers (5)

Guffa
Guffa

Reputation: 700770

Put the keys in an array:

string[] keys = {
  "PRODUCTID", "PRODUCTCODE", "PRODUCT", "CLEAN_URL",
  "WEIGHT", "LIST_PRICE", "DESCR", "FULLDESCR",
  "KEYWORDS", "TITLE_TAG", "META_KEYWORDS", "META_DESCRIPTION",
  "AVAIL", "RATING", "FORSALE", "SHIPPING_FREIGHT",
  "FREE_SHIPPING", "DISCOUNT_AVAIL", "MIN_AMOUNT", "LENGTH",
  "WIDTH", "HEIGHT", "LOW_AVAIL_LIMIT", "FREE_TAX",
  "CATEGORYID", "CATEGORY", "POS", "MEMBERSHIP",
  "PRICE", "THUMBNAIL", "IMAGE", "TAXES",
  "ADD_DATE", "VIEWS_STATS", "SALES_STATS", "DEL_STATS",
  "SMALL_ITEM", "SEPARATE_BOX", "ITEMS_PER_BOX", "GENERATE_THUMBNAIL",
  "RETURN_TIME", "MANUFACTURERID", "MANUFACTURER"
};

Now you can make a dictionary from that:

string[] row = productsList[i];

product.row1 =
  Enumerable.Range(0, row.Length).ToDictionary(i => keys[i], i => row[i]);

Upvotes: 1

IdeaHat
IdeaHat

Reputation: 7881

Yup (on a computer without visual studio, so I can't verify that I've got no bugs)

List<string> keys = new List<string>{"PRODUCTID","PRODUCTCODE"\*ect*\}
Dictionary<string,string> dict = new Dictionary<string,string>
for (int i = 0; i < keys.Count; i++)
{
    dict[keys[i]]=row[i];
}

And going back for (int i = 0; i < keys.Count; i++) { row[i] = dict[keys[i]]; } This isn't functionally any different than what you have though, and has the added restraint that you can't check the keys before compile time.

You could use a reflection trick to fill in the properties automagically using the list instead of using a dictionary:

http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx

for (int i = 0; i < keys.Count; i++)
{
 this.GetType().InvokeMember(keys[i],
     BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
     Type.DefaultBinder, obj, row[i]);
}

This is all providing you are setting properties and not members.

I would still make the list of properties by hand though, C# doesn't care about the return order.

Upvotes: 1

Jason Watkins
Jason Watkins

Reputation: 3785

Given that each value has a unique key, it isn't trivially possible to use a loop here. No matter how you go about it, you will have to list all of the keys somwhere. That said, you could define all of the keys in a static array and use a loop like so:

string[] keys = new [] {"PRODUCTID", "PRODUCTCODE", ... };
Dictionary<string, string> ProductAttributes = new Dictionary<string,string>();

for(int i = 0, i < row.Length, i++)
{
    ProductAttributes[keys[i]] = row[i];
}

Note, however, that doing this means that you lose all of the static checking that you get from having properties. By placing everything in a dictionary, you are introducing potential run time errors from mistyped key names.

Upvotes: 1

rein
rein

Reputation: 33465

Put that logic into an overloaded constructor for Product so you can do this:

Product product = new Product(productsList[i]);

There's not much you can do to short circuit this logic. It has to live somewhere unless you can encode more metadata into the row.

Upvotes: 1

redtuna
redtuna

Reputation: 4600

// you only have to do this once
string[] labels = new string [] { "PRODUCTID", "PRODUCTCODE", ...

and then you can have a dictionary and load it like that:

Dictionary<string,string> d = new Dictionary<...>

for (int i=0; i<labels.Count; i++) {
    d[labels[i]] = row[i];
}

Upvotes: 1

Related Questions