In C# Convert List<dynamic> to List<string>

Given

var dList = new List<dynamic>() { /*...initialize list */ };

If you are interested in extracting all the strings in the collection, ignoring all other types, you can use:

// Solution 1: Include only strings, no null values, no exceptions thrown
var strings = dlist.OfType<string>().ToList();

If you are certain that all the items in the list are strings (it will throw an exception if they are not), you can use:

// Solution 2: Include strings with null values, Exception for other data types thrown
var strings = dlist.Cast<string>().ToList();

If you want the default string representation, with null for null values, of all the items in the list, you can use:

// Solution 3: Include all, regardless of data type, no exceptions thrown
var strings = dlist.Select(item => item?.ToString()).ToList();

Given

List<dynamic> dList;

You can use

var sList = List<String>.from(dlist);

to convert a List<dynamic> to List<String>

Tags:

C#