foreach循环

一、foreach操作数组

int[] i = new int[] { 1, 2, 3, 4, 5,67, 8 };
            foreach(int i1 in i)
            {
                MessageBox.Show(i1.ToString());
            }

二、foreach操作集合

List<int> ints = new List<int>(){1,2,3,4,5,6,7};
           /* ints.Add(1);
            ints.Add(2);
            ints.Add(3);
            ints.Add(4);
            ints.Add(5); */
            foreach(int item in ints)
            {
                MessageBox.Show(item.ToString());
            }

三、foreach操作字典

Dictionary<string, string> dictionary = new Dictionary<string, string>() 
            { 
                { "AA", "aa" }, 
                { "BB", "bb" } 
            };
            foreach(KeyValuePair<string,string> item in dictionary)
{ string key = item.Key; string value = item.Value; MessageBox.Show(key+"-"+value); }

四、foreach操作自定义List

//实体类
namespace
List { public class Person { public string Name { get; set; } public string Sex { get; set; } public int Age { get; set; } public int Height { get; set; } public List<Person> GetUserList() //封装一个方法得到person的list集合 { List<Person> List = new List<Person>(); List.Add(new Person { Name="B", Sex="", Age = 18, Height=167, }); List.Add(new Person { Name = "A", Sex = "", Age = 19, Height = 160, }); return List; } } }
 //实现
Person person = new Person(); List<Person> person1 = person.GetUserList(); foreach (Person item in person1) { MessageBox.Show(item.Name+item.Sex+item.Age+item.Height); } Person person = new Person(); List<Person> person1 = person.GetUserList(); foreach (Person item in person1) { MessageBox.Show(item.Name+item.Sex+item.Age+item.Height); }

 

posted @ 2021-07-09 13:49  F11  阅读(304)  评论(0)    收藏  举报