将列表元素拼接成由分隔符分隔的字符串

ExpandedBlockStart.gif 代码
public   static   class  EnumerableExtension
{
    
///   <summary>
    
///  将列表元素拼接成由splitter分隔的字符串
    
///   </summary>
    
///   <example>
    
///      拼接字符串:
    
///           <c> new List&lt;string&gt; { "aa", "bb", "cc" }.Montage(p => p, ","); // 返回:"aa,bb,cc" </c>
    
///      拼接对象属性:
    
///           <c> new List&lt;string&gt; { "aa", "bbb", "c" }.Montage(p => p.Length.ToString(), ","); // 返回:"2,3,1" </c>
    
///      拼接枚举值:
    
///           <c> new List&lt;DomainType&gt; { DomainType.GuanHao, DomainType.YaoJiKe }.Montage(p => ((int)p).ToString(), ","); // 返回:"1,2" </c>
    
///      拼接枚举名:
    
///           <c> new List&lt;DomainType&gt; { DomainType.GuanHao, DomainType.YaoJiKe }.Montage(p => p.ToString(), ","); // 返回:"GuanHao,YaoJiKe" </c>
    
///   </example>
    
///   <typeparam name="T"></typeparam>
    
///   <param name="source"></param>
    
///   <param name="toString"> 将列表元素转换为字符串的委托 </param>
    
///   <param name="splitter"> 分隔符(可为空) </param>
    
///   <returns></returns>
     public   static   string  Montage < T > ( this  IEnumerable < T >  source, Func < T,  string >  toString,  string  splitter)
    {
        StringBuilder result 
=   new  StringBuilder();
        splitter 
=  splitter  ??   string .Empty;
        
foreach  (T item  in  source)
        {
            result.Append(toString(item));
            result.Append(splitter);
        }
        
string  resultStr  =  result.ToString();
        
if  (resultStr.EndsWith(splitter))
            resultStr 
=  resultStr.Remove(resultStr.Length  -  splitter.Length, splitter.Length);
        
return  resultStr;
    }

    
///   <summary>
    
///  从泛型IEnumerable创建一个泛型List,每个元素由converter进行类型转换。
    
///   </summary>
    
///   <example>
    
///      将枚举List转换为Int32 List:
    
///           <c> new DomainType[] { DomainType.GuanHao, DomainType.YaoJiKe }.ToList(p => (int)p); // 返回:List&lt;int&gt; </c>
    
///   </example>
    
///   <typeparam name="TSource"></typeparam>
    
///   <typeparam name="TResult"></typeparam>
    
///   <param name="source"></param>
    
///   <param name="converter"></param>
    
///   <returns></returns>
     public   static  List < TResult >  ToList < TSource, TResult > ( this  IEnumerable < TSource >  source, Func < TSource, TResult >  converter)
    {
        List
< TResult >  result  =   new  List < TResult > ();
        
foreach  (TSource item  in  source)
        {
            result.Add(converter(item));
        }
        
return  result;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值