1

So I have this string array of elements:

string[] words = { "My", "name", "is", "Jack" }; 

I want each element in this array linked to a specific value (decimal) but every single time I press a button for this elements to appear(in text) let's say in a textbox or a label I want to be able to press a second button that updates that decimal that is linked with the elements.Each element has its' own specific value (let's call it weight). I have tried with:

decimal weight1 = 0; 
words[0] = Convert.ToString(weight1); 
label1.Text = Convert.ToString(words[0]);

But all it does is that it assigns the value to the element (changes it) and I don't want that. I want them to appear as text but only link the element not change it, and update its' linked value on the background.

The element:

"My" is linked to weight1 The element "name" is linked to weight2, name => weight3, Jack => weight4.

How can I do that?

I am open to other suggestions if this is not possible with arrays, maybe classes or interfaces...

1
  • Have you thought of using enums Commented Dec 8, 2019 at 2:31

2 Answers 2

3

Sounds like you need a custom class to define your schema. Rather than an array of strings, you should define a class that looks like the below:

public class WeightedWord
{
      public WeightedWord(string word, decimal weight)
      {
           Word = word;
           Weight = weight;
      }

      public string Word { get; set; }
      public decimal Weight { get; set; }
}

You'lll then be able to assign an individual weight to each word.

Your array will look something like this:

WeightedWord[] weightedWords = { new WeightedWord("My", .1), 
                                 new WeightedWord("name", .2),
                                 new WeightedWord("is", .3),
                                 new WeightedWord("Jack", .4) }; 

In your button press action, you can access the specific object you want to update.

weightedWords[0].Weight = .7;
Sign up to request clarification or add additional context in comments.

1 Comment

Consider a Generic List<WeightedWord> instead of array
1

Sounds like you just need a Dictionary<string, decimal>. Use the keyword as your lookup and then you can simply reference it to always pull the respective numeric value.

var lookup = new Dictionary<string, decimal>()
{
    { "My", 0.0m },
    { "name", 0.0m },
    { "is", 0.0m },
    { "Jack", 0.0m },
};

Then you can update by word whenever you need to:

lookup["My"] += 1;
lookup["name"] += 0.5;

Or if in an event handler (WinForms button click for example) then whatever the text of the button is can drive it:

lookup[(sender as Button).Text] += 1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.