使用扩展方法对IEnumerable<T>扩展,来生成分割符字符串.看这个方法:
/// <summary> /// Get the delimited string. /// </summary> /// <typeparam name="T">T</typeparam> /// <param name="list">The list.</param> /// <param name="delimiter">The delimiter.</param> /// <param name="action">The action.</param> /// <returns>string</returns> public static string ToDelimitedString<T>(this IEnumerable<T> list, string delimiter, Func<T, string> action) { var sb = new System.Text.StringBuilder(); foreach (var t in list) { sb.Append(action.Invoke(t)); sb.Append(delimiter); } sb.Remove(sb.Length - delimiter.Length, delimiter.Length); return sb.ToString(); }
public class Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }
UnitTest,这里是”,”分隔符,当然你可以用其它的:
/// <summary> /// Tests the delimited string. /// </summary> /// <remarks>author:Petter Liu http://wintersun.cnblogs.com </remarks> [Test] public void TestDelimitedString() { var list = new List<Person> { new Person() {FirstName = "Petter", LastName = "Liu"}, new Person() {FirstName = "Tina", LastName = "Lin"}, new Person() {FirstName = "David", LastName = "Pan"}, new Person() {FirstName = "John", LastName = "Robert"} }; var result=list.ToDelimitedString(",", p => string.Format("{0} {1}", p.FirstName, p.LastName)); System.Diagnostics.Debug.WriteLine(result); // Petter Liu,Tina Lin,David Pan,John Robert }
用好扩展方法,能为我们省很多的代码量.
Author:PetterLiu http://wintersun.cnblogs.com