namespace dic2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        private void button1_Click(object sender, EventArgs e)
        {
            Dictionary<int, string> datatable = new Dictionary<int, string>();
            datatable.Add(1, "hello 1");
            datatable.Add(2, "hello 2");
            var list = datatable.ToList();
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Value == "hello 2")
                {
                    list[i].Value = "hello";//报错
                     MessageBox.Show(list[i].Value, "out");
                }
            }
        }
    }
}怎样既实现遍历又能修改value值呢?
忘大牛赐教!!!

解决方案 »

  1.   

    Dictionary<int, string> datatable = new Dictionary<int, string>();
    datatable.Add(1, "hello 1");
    datatable.Add(2, "hello 2");
    int[] keys = datatable.Keys.ToArray();
    for (int i = 0; i < keys.Length; i++)
    {
        if (datatable[keys[i]] == "hello 2")
        {
            datatable[keys[i]] = "hello";
        }
    }
      

  2.   

    namespace dic2
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            struct hello
            {
                public int a;
                public string b;
                public  hello(int A, string B)
                {
                    a = A;
                    b = B;
                }        }
            private void button1_Click(object sender, EventArgs e)
            {
                Dictionary<int, hello> datatable = new Dictionary<int, hello>();
                hello hi=new hello(1,"hello1");
                datatable.Add(1, hi);
                hi=new hello(2,"hello2");
                datatable.Add(2, hi);            int[] keys = datatable.Keys.ToArray();
                
                for(int i=0;i<keys.Length;i++)
                {
                if(datatable[keys[i]].a==1) 
                {
                    datatable[keys[i]].b = "ok";//出错,无法修改该处,因为左侧不是变量(系统提示)
                    MessageBox.Show(datatable[keys[i]].b, "");
                }
                }
                
            }
        }
    }
    这个原因是???
      

  3.   

    你用class吧。
    struct不行的。原因我详细的分析在博客中了
    http://blog.csdn.net/wuyazhe/archive/2010/06/18/5676881.aspx