var dlist = new List<dynamic>()
{
    "Guangzhou",
    "Zhuhai",
    "Shenzhen"
};

提取集合中的所有字符串,忽略所有其他类型,可以使用:
// Solution 1: Include only strings, no null values, no exceptions thrown
var strings = dlist.OfType<string>().ToList();


如果您确定列表中的所有项目都是字符串(如果不是,则会抛出异常),您可以使用:
// Solution 2: Include strings with null values, Exception for other data types thrown
var strings = dlist.Cast<string>().ToList();

如果您想要列表中所有项目的默认字符串表示形式,带有nullfornull值,您可以使用:
// Solution 3: Include all, regardless of data type, no exceptions thrown
var strings = dlist.Select(item => item?.ToString()).ToList();

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-12
猜你喜欢
  • 2022-12-23
  • 2021-06-26
  • 2022-12-23
  • 2022-12-23
  • 2021-10-04
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案