• 用扩展方法生成分割符字符串


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

  • 相关阅读:
    异常日志以及非异常日志记录方法
    oracle 监测数据库是否存在指定字段
    listview禁止双击一条之后选中复选框按钮的方法
    oracle 的rowid和rownum
    修改文件的名字的写法
    使用C#读取XML节点,修改XML节点
    BZOJ 1004: [HNOI2008]Cards
    P5022 旅行 (NOIP2018)
    P5021 赛道修建 (NOIP2018)
    P5020 货币系统 (NOIP2018)
  • 原文地址:https://www.cnblogs.com/wintersun/p/1490310.html
Copyright © 2020-2023  润新知