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源碼如下:

 

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