[英]In C# Convert List<dynamic> to List<string>
Suppose I have a List<dynamic>
object containing strings:假设我有一个包含字符串的
List<dynamic>
对象:
var dlist = new List<dynamic>()
{
"test",
"test2",
"test3"
};
Is there any efficient way of converting this into a proper List<string>
object?有没有什么有效的方法可以将其转换为正确的
List<string>
对象? 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?我知道我可以遍历这个列表并将每个元素转换为一个字符串,然后将它添加到结果列表中,但也许一些 Linq 魔术可以在一行中完成这个技巧?
I tried using some Select()
combined with ToList()
and Cast<string>
, but to no avail.我尝试将一些
Select()
与ToList()
和Cast<string>
结合使用,但无济于事。 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.编辑:好的,关于“为什么 Cast 不适合你”的评论 - 看起来我在收到的数据方面遇到了另一个问题(我正在使用 Dapper),这就是它不起作用的原因。 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:如果您想要列表中所有项目的默认字符串表示形式(
null
null
,您可以使用:
// 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
这个答案适用于
dart/flutter
Given给定的
List<dynamic> dList;
You can use你可以使用
var sList = List<String>.from(dlist);
to convert a List<dynamic>
to List<String>
将
List<dynamic>
转换为List<String>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.