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);
var singleString = string.Join(",", _values.ToArray() );
","
by String.Empty
if the commas are already in the data.
string.Join
is probably the simplest method of achieving the desired result.
Aug 5, 2010 at 12:00
Join
and Concat
take IEnumerable
, and you don't need ToArray
. So, it depends.
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);
String.Join(
",",
_tbl.AsEnumerable()
.Select(r => r.Field<int>("ID").ToString())
.ToArray())
Try this:
var _values = _tbl.AsEnumerable().Select(x => x);
string valueString = _values.ToList().Aggregate((a, b) => a + b);
ToList
? Why not just _tbl.AsEnumerable().Select(x => x).Aggregate((a, b) => a + b);
?
Aug 5, 2010 at 11:56
Select(x => x)
makes not sense because AsEnumerable()
already makes table IEnumerable<DataRow
. ToList()
makes no sense, Aggregate()
is a member if IEnumerable<T>
not List<T>
Aug 5, 2010 at 12:09
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.
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());
String output = String.Concat(_tbl.AsEnumerable().ToArray());
would do the same, no ? (without the Select
)
Select(x => x);
makes absolutely no sense, especially in your case