c# - List of values to list of strings -
how convert it:
var values = new list<object> { 1, 5, "eee", myenum.value };
to
var stringvalues = new list<object> { "1", "5", "eee", myenum.value.tostring() };
but in fast way?
first, it's not clear whether question different convert list(of object) list(of string); if is, should clarify particular situation.
the straight-forward solution use linq: var stringvalues = values.select(v => (object) v.tostring()).tolist();
note cast object
match code above.
it's not clear why you'd want result list<object>
instead of list<string>
. also, should prefer work ienumerable<>
instead of converting list<>
. preferred code be
var stringvalues = values.select(v => v.tostring());
if you're doing type of thing lot, might find extension method useful
static class listextensions { public static ienumerable<string> asstrings(this list<object> values) { return values.select(v => v.tostring()); } }
you use like:
var stringvalues = values.asstrings();
depending on needs, may want more more sophisticated string conversion object.tostring()
. convert.tostring()
tries first find iconvertable
, iformattable
interfaces before calling tostring()
.
var stringvalues = values.select(v => convert.tostring(v));
Comments
Post a Comment