IEnumerable to string delimited with commas?

C#asp.netLinqado.netDatatable

C# Problem Overview


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,101

How can i rewrite the following to get a single string

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

C# Solutions


Solution 1 - C#

var singleString = string.Join(",", _values.ToArray() );

Solution 2 - C#

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);    

Solution 3 - C#

 String.Join(
      ",",
      _tbl.AsEnumerable()
          .Select(r => r.Field<int>("ID").ToString())
          .ToArray())

Solution 4 - C#

Try this:

var _values = _tbl.AsEnumerable().Select(x => x);
string valueString = _values.ToList().Aggregate((a, b) => a + b);

Solution 5 - C#

You can use MoreLINQ extension

var singleString = _values.ToDelimitedString(",");

Solution 6 - C#

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.

Solution 7 - C#

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());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser160677View Question on Stackoverflow
Solution 1 - C#Winston SmithView Answer on Stackoverflow
Solution 2 - C#Alex HumphreyView Answer on Stackoverflow
Solution 3 - C#abatishchevView Answer on Stackoverflow
Solution 4 - C#Tim S. Van HarenView Answer on Stackoverflow
Solution 5 - C#Ad23View Answer on Stackoverflow
Solution 6 - C#honzakuzel1989View Answer on Stackoverflow
Solution 7 - C#cjkView Answer on Stackoverflow