Hi guys,

I have a class which contains similar property names like:

  public class numbers()
        public int Number1

        Public int Number2

I then have a method where I iterate through a collection and want to assign a particular property with a value based on the interation count. So if is the first interation Number1 should get the value.

What im trying to do is something like the following

    for(var i = 1; i < collection.count; i++)
     Number[i] = colllection[i].Number[i];
` }

This is obviously given me an error on the property. Does anyone know how can i add the interation number on the property name which would make it look like what my property is actually called?

Thank you

Recommended Answers

All 2 Replies

AFAIKS your class Numbers does not contain properties, just fields.
Did you already considered a Dictionary?

It appears you are trying to treat you ints as a collection ... which you can probably assume will NOT work. ddanbe does bring up a good idea, that you could use a dictionary.

This gives you a "key" based on the 'i' value (which is kind of like "Number1", "Number2", ext), that you can assign a value to. Just be aware, you can add a new index to a dictionary, but once you do, that key is set and can't be changed. The Value for the key can, however.

You'd have something like

Dictionary<int, int> Number = new Dictionary<int, int>();

for(var i = 1; i < collection.count; i++)
    Number.Add(i, collection[i].Number[i]);

That should do the trick for you (I am kind of curious what you are trying to do here, as you call the index for the collection and then the index for the Number property, which means in collection index 5, you are accessing the 5th index of the Number property, which I could see turning into an out of bounds type error)

commented: Nice advice +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.