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);
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
var singleString = string.Join(",", _values.ToArray() );
Method 2
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);
Method 3
String.Join(
",",
_tbl.AsEnumerable()
.Select(r => r.Field<int>("ID").ToString())
.ToArray())
Method 4
Try this:
var _values = _tbl.AsEnumerable().Select(x => x); string valueString = _values.ToList().Aggregate((a, b) => a + b);
Method 5
You can use MoreLINQ extension
var singleString = _values.ToDelimitedString(",");
Method 6
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.
Method 7
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());
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0