Suppose I have a List<dynamic>
object containing strings:
var dlist = new List<dynamic>()
{
"test",
"test2",
"test3"
};
Is there any efficient way of converting this into a proper List<string>
object? I know I can iterate over this list and cast each element to a string, then add this to the result list, but maybe some Linq magic could do the trick in one line?
I tried using some Select()
combined with ToList()
and Cast<string>
, but to no avail. How should this be done properly?
Note : By saying "efficient" I mean of course number of lines of code. I do not take execution time or performance into account. Also - let's suppose I do not need to type check, there will always be strings only in this dynamic list.
EDIT: Okay, so in regards to comments on "why Cast wasn't working for you" - looks like I had another problem regarding the data I receive (I'm using Dapper) and that's why it didn't work. Sorry for the confusion, I thought my list converting was wrong while the problem was not related to this.
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();
This answer is for
dart/flutter
Given
List<dynamic> dList;
You can use
var sList = List<String>.from(dlist);
to convert a List<dynamic>
to List<String>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.