IEnumerable to string

前端 未结 7 2132
既然无缘
既然无缘 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:18
    var singleString = string.Join(",", _values.ToArray() );
    
    0 讨论(0)
  • 2021-02-05 00:22

    Write an extension method such as

    public static String AppendAll(this IEnumerable<String> 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<String>, call:

    var _values = _tbl.AsEnumerable().Select(x => x).AppendAll(String.Empty);    
    
    0 讨论(0)
  • 2021-02-05 00:30

    You can use MoreLINQ extension

    var singleString = _values.ToDelimitedString(",");
    
    0 讨论(0)
  • 2021-02-05 00:33

    I had a similar issue with general Array type and i solved it as follows

    string GetMembersAsString(Array array)
    {
        return string.Join(",", array.OfType<object>());
    }
    

    Note that call OfType<object>() is mandatory.

    0 讨论(0)
  • 2021-02-05 00:36
     String.Join(
          ",",
          _tbl.AsEnumerable()
              .Select(r => r.Field<int>("ID").ToString())
              .ToArray())
    
    0 讨论(0)
  • 2021-02-05 00:36

    You can cheat with this:

    String output = "";
    _tbl.AsEnumerable().Select(x => output += x).ToArray(); 
    // output now contains concatenated string
    

    Note ToArray() or similar is needed to force the query to execute.

    Another option is

    String output = String.Concat(_tbl.AsEnumerable().Select(x=>x).ToArray());
    
    0 讨论(0)
提交回复
热议问题