C# DYNAMIC SELECT LIST OF STRINGS

Jayne Spooner

Total Post:21

Points:147
Posted by  Jayne Spooner
C#  .NET  String  list 
 1007  View(s)
Ratings:
Rate this:
I'm trying to get List of strings from my dynamic object list and it keeps saying that:

Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<dynamic>' to 'System.Collections.Generic.List<string>'
I'm selecting a property and use .ToString() on it:

var objects = new List<dynamic>();
//filling objects here

List<string> things = objects.Select(x => x.nameref.ToString()).ToList();
So isn't it a valid List of strings? Why compiler is assuming that this list is of type dynamic?

I've tried also converting from this answer, but it keeps giving me same error.

Anyone knows how to make it List<string>?

Why isn't it working? Because you can make mess like this:

public class Test
{
    public int ToString()
    {
        return 0;
    }
}
and compiler won't know if ToString returns string or int.
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: 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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!