C# Dynamic select List of strings
You need to cast the items, like so:
List<string> things = objects.Select(x => x.nameref.ToString()).Cast<string>().ToList();
The reason why it's not recognizing that ToString()
returns a string is that it's called on a dynamic
object, and the method binding is done at runtime, not compile time.
Although Rob's answer works fine, let me suggest an alternative: Cast nameref
to the correct type (replace (object)
by a more specific cast, if you happen to know the type of nameref
):
List<string> things = objects.Select(x => ((object)x.nameref).ToString()).ToList();
The advantage of that solution is that ToString
is statically resolved. Thus, the method call is
guaranteed to return
string
, since the compiler knows that you are calling Object.ToString() (or an overridden variant thereof) andfaster and cleaner. This solution keeps dynamic resolution to the absolute minimum needed (i.e., the resolution of
x.nameref
). Typos in the call toToString
are caught by the compiler.
(Of course, if the type of nameref
happens to be string, you can just drop the call to ToString()
, making your code even cleaner and shorter.)
You could try using Cast, like so:
List<string> things = objects.Select(x => x.nameref).Cast<string>().ToList();
You could also try casting in the Select
itself:
List<string> things = objects.Select(x => x.nameref as string).ToList();