快速拼凑字符串

namespace StringJoin {
    class Program {
        static void Main(string[] args) {
        List<Product> products=new List<Product>()
        {
            new Product(){ProductID=1,ProductName="Iphone5s"},
            new Product(){ProductID=2,ProductName="Iphone6s"}
        };

            //传统的拼凑
            string _productid = "";
            foreach (var product in products)
            {
                if (_productid != "")
                {
                    _productid = _productid + "," + product.ProductID;
                }
                else
                {
                    _productid = product.ProductID.ToString();
                }
            }
            Console.WriteLine(_productid);
            //委托操作
            _productid = "";
            products.ForEach(p =>
            {
                if (_productid != "") {
                    _productid = _productid + "," + p.ProductID;
                } else {
                    _productid = p.ProductID.ToString();
                }
            });
            Console.WriteLine(_productid);

            //linq string.join
            _productid = "";
            //string.Join("", s.Select(it => string.IsNullOrWhiteSpace("") ? it : "" + "," + it));
            _productid=string.Join(",", products.Select(it => it.ProductID.ToString()));

            Console.WriteLine(_productid);
            Console.Read();
        }
    }

    class Product
    {
        public  int ProductID { get; set; }
        public  string ProductName { get; set; }
    }
}

记录而已

posted on 2014-05-21 10:40  ~紫鱼~  阅读(334)  评论(0编辑  收藏  举报