hi, i wants to take the items from a listbox and then store to a dictionary list like this:
Dictionary<string, double> sortList3 = new Dictionary<string, double>();
In the dictionary, the key is string and value is double.

The listbox content is as below:
{1 2} 4
{1 4} 6
{1 5} 7
{1 3 4} 8

The first column i want store as key, and second colum want to be the value of the dictionary list, what should do? Please help me, i really have no idea with this problem..

You can use foreach loop to your listbox to fetch individual item and add it to the listbox. However, the contents of your listbox items are not comfortable with the type double.

The listbox content is as below:
{1 2} 4
{1 4} 6
{1 5} 7
{1 3 4} 8

1st column is what is in the brackets? And the value out of brackets is your 2nd column, which would be the Value of the dictionary?

Edited 5 Years Ago by Mitja Bonca: n/a

Check out this code:

public partial class Form1 : Form
    {
        Dictionary<string, double> dic = new Dictionary<string, double>();
        public Form1()
        {
            InitializeComponent();
            listBox1.Items.AddRange(new string[] { "{1 2} 4", "{1 4} 6", "{1 5} 7", "{1 3 4} 8" });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string line = listBox1.SelectedItem.ToString();
            string _key = Regex.Match(line, @"{(.*?)}").Groups[1].Value;
            string _value = line.Remove(0, ((line.IndexOf("}") + 2)));
            double dValue = 0;
            if (double.TryParse(_value, out dValue))
            {
                if (dic.ContainsKey(_key))
                    dic[_key] = dValue;
                else
                    dic.Add(_key, dValue);

                //I will even remvoe the selected item from the listBox (so you donw have duplicates).
                //If you dont want to remove, simply dont use this code.
                listBox1.Items.Remove(line);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //check what have you stored into the dictionary:
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("These is what you have stored into the dictionary<string, double> :");
            foreach (KeyValuePair<string, double> kvp in dic)
            {
                sb.AppendLine(String.Format("Key: {0}, Value: {1}", kvp.Key, kvp.Value));
            }
            MessageBox.Show(sb.ToString());
        }
    }

Mitja

This question has already been answered. Start a new discussion instead.