zoukankan      html  css  js  c++  java
  • 用扩展方法生成分割符字符串

    使用扩展方法对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

  • 相关阅读:
    域环境的搭建 (超级详细)
    sqli-labs(10)
    sqli-labs(9)
    mysql源码安装(5.1)
    查看mysql apache php nginx的编译参数
    LAMP的安装
    Mysql的安装(二进制免编译包) 5.1版本
    更改yum网易 阿里云的yum源。
    yum安裝的包如何保留到本地
    磁盘分区
  • 原文地址:https://www.cnblogs.com/wintersun/p/1490310.html
Copyright © 2011-2022 走看看