list扩展方法ForEach原理(where,FirstOrDefault同理!)

5075人阅读 2021/3/11 9:24 总访问:671291 评论:0 收藏:0 手机
分类: Csharp
      //ForEach的原理就是使用循环
      
      //委托使用循环
       public static void MyForEach<T>(this List<T> item, Action<T> action)
        {
            for (int i = 0; i < item.Count; i++)
            {
                action(item[i]);
            }
        }
        //List也可以替换为List的父类IEnumerable(可使用的类型更广)
        public static void MyForEach<T>(this IEnumerable<T> list, Action<T> action)
         {
            foreach (T item in list)
             {
                action(item);
             }
         }
        
        
        
        
        
        
        //使用自定义的ForEach
           list.MyForEach(item =>
            {
                Console.WriteLine(item.UserName, item.Age, item.Address));
            });


评价
脚踏实地,一步一个脚印
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术