zoukankan      html  css  js  c++  java
  • Lambda 遍历

    遍历列表元素

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ForEachDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(LambdaAndEach()); //输出:'1','4','5','6','7','8','9','10'
                Console.ReadKey();
    
            }
    
            public static string LambdaAndEach()
            {
                //数据源
                var retList = new List<int>() { 1, 4, 5, 6, 7, 8, 9, 10 };
    
                var sbBuilder = new StringBuilder();
    
                retList.ForEach(item =>
                {
                    //如果是最后一个元素则用('item')包裹,否则用('item',)包裹元素
                    if (item == retList[retList.Count - 1])
                    {
                        sbBuilder.Append("'" + item + "'");
                    }
                    else
                    {
                        sbBuilder.Append("'" + item + "',");
                    }
                });
    
                return sbBuilder.ToString();
            }
    
        }
    }
    

    例二:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        class User
        {
            public Guid Id { get; set; }
            public string UserName { get; set; }
            public string Pwd { get; set; }
        }
        class Program
        {
            static void Main(string[] args)
            {
                //数据源
                var dataSource = new List<User>()
                {
                    new User() {Id = Guid.NewGuid(), UserName = "admin", Pwd = "123"},
                    new User() {Id = Guid.NewGuid(), UserName = "zhang", Pwd = "345"},
                    new User() {Id = Guid.NewGuid(), UserName = "liu", Pwd = "999"}
                };
    
                var uids = dataSource.Select(u => u.Id.ToString());
    
                Console.WriteLine("所有用户ID,用空格|隔开
    {0}", string.Join(" | ", uids));
                //输出:所有用户ID,用空格|隔开
                //44927238 - 8ce7 - 4581 - 91ec - 4797712dc85a | 116037c7 - 4275 - 4491 - 9a2a - afb887ea2cf0 | 2c157abc - 8f13 - 4394 - b5e3 - 4778a9a420df
                Console.ReadKey();
    
            }
        }
    }
    

      

      

  • 相关阅读:
    JavaScript高级程序设计学习笔记--变量、作用域和内存问题
    JavaScript高级程序设计学习笔记--基本概念
    Silverlight 动画性能
    Silverlight动画之 Animation Easing
    Silverlight 动画详解
    WCF重写ServiceHost,实现独立配置文件
    WP8 双击返回键退出
    Asp.Net之自定义表达式构造器(ExpressionBuilder)
    通过configSource提高web.config配置灵活性
    C# 操作IIS方法集合
  • 原文地址:https://www.cnblogs.com/wanghaibin/p/6218461.html
Copyright © 2011-2022 走看看