快速拼凑字符串
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; } } }
记录而已