Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable to string delimited with commas?

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); 
like image 365
user160677 Avatar asked Aug 05 '10 11:08

user160677


People also ask

How do I create a comma separated string from a List of strings in C#?

The standard solution to convert a List<string> to a comma-separated string in C# is using the string. Join() method. It concatenates members of the specified collection using the specified delimiter between each item.

How do you join a List of strings with a comma?

In Java, we can use String. join(",", list) to join a List String with commas.

How do you convert a comma separated string to an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How do you convert a List to a comma separated string in python?

Use the join() Function to Convert a List to a Comma-Separated String in Python. The join() function combines the elements of an iterable and returns a string. We need to specify the character that will be used as the separator for the elements in the string.


2 Answers

var singleString = string.Join(",", _values.ToArray() ); 
like image 114
Winston Smith Avatar answered Oct 16 '22 08:10

Winston Smith


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);     
like image 24
Alex Humphrey Avatar answered Oct 16 '22 07:10

Alex Humphrey