在 C# 中將 List 轉換為 List


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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。