C# foreach的实现 foreach(new {Name=""} s in collection)

目的就是为了实现类似的写法

foreach(new {Name=String.Empty} Ele in (IEnumrable)Collection)

{

      // 要执行的操作...

}

 

适用场景... 

 var datas=from student in StudentCollection select  new{studentName=student.Name };

把datas存入ViewState中,若在一个方法内 则可以直接 foreach...

 

问题就出现在别的页面在此访问ViewState就无法使用foreach(var ele ...)了

 

具体请查看

http://topic.csdn.net/u/20100820/01/ef01ef42-8c67-4901-a039-5dcf0d0fdf00.html

 

最后看了大家的回答,自己思考后...实现了一个简单的方法...还是反射

 

用起来方便了,稍加改进效果应该还是不错的

 

第一步,声明一个类(相当于DataSourceTemplate):

   public class Stu
    {
        public Stu() { }

         //这里我只要3个属性就行了
         public Stu(String name,String mail,String address)
        {
            this.Name = name;
          
            this.Mail = mail;
           
            this.Address = address;
        }

        public String Name { get; set; }

        public String Mail { get; set; }

        public String Address { get; set; }

        public String Phone { get; set; }
    }

 

第二步 狂加数据:

 

            List< Stu> larr = new List< Stu>();
          
            larr.Add(new Stu("联想", "[email protected]", "中国"));
           
            larr.Add(new Stu("神州", "[email protected]", "美国"));
           
            larr.Add(new Stu("惠普", "[email protected]", "俄罗斯"));
           
            larr.Add(new Stu("苹果", "[email protected]", "印度"));

 

第三步 开始调用方法:

 

           CustomForeach customEach = new CustomForeach();       

 

           customEach.ForeachOfClass(new { Name="", Mail = "", Address = "" }, larr,
                (propertyName, originValue,currentValue) =>
            {
                 Response.Write(String.Format("{0}={1}", propertyName, currentValue));

                 //获取当前数据集合的元素索引 customEach.Elementindex

                 //获取当前数据集合的元素第几个属性索引 customEach.PropertyIndex

            });

 

整个使用过程结束...

 

 

CustomForeach源码如下:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章