IEnumerable to string

前端 未结 7 2139
既然无缘
既然无缘 2021-02-04 23:55

I have a DataTable that returns

IDs
,1
,2
,3
,4
,5
,100
,101

I want to convert this to single string value, i.e:

,1,2,3,4,5,100         


        
7条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 00:22

    Write an extension method such as

    public static String AppendAll(this IEnumerable collection, String seperator)
    {
        using (var enumerator = collection.GetEnumerator())
        {
            if (!enumerator.MoveNext())
            {
                return String.Empty;
            }
    
            var builder = new StringBuilder().Append(enumerator.Current);
    
            while (enumerator.MoveNext())
            {
                builder.Append(seperator).Append(enumerator.Current);
            }
    
            return builder.ToString();
        }
    }
    

    and assuming the result of your previous expression is IEnumerable, call:

    var _values = _tbl.AsEnumerable().Select(x => x).AppendAll(String.Empty);    
    

提交回复
热议问题