c# - 如何将 List<Anonymous Type> 转换为 List<string>

标签 c# linq-to-sql .net-4.0 casting anonymous-types

我想转换一个 List<AnonymousType>List<string> .我有以下代码:

var lkpiTodisplay = _MGMTDashboardDB.KPIs.Where(m => m.Compulsory == true && m.Active == true)
                                         .Select(m => new
                                         {
                                             KPI_Name = m.Absolute == true ? m.KPI_Name : (m.KPI_Name + "%")
                                         }).ToList();

for(int i=1; i<= BusinessTargetCol; i++)
{
   lkpiTodisplay.Add(new
   {
      KPI_Name = "Business Target"
   });
}

此代码创建一个 List<AnonymousType> .然后我想将此列表分配给变量 List<string> ,如下代码所示:

DashboardViewModel lYTMDashboard = new DashboardViewModel()
{
      KPIList = (List<string>) lkpiTodisplay,
      //other assignments
};

类型转换不起作用。我怎样才能转换变量?欢迎修改第一个代码片段的其他解决方案,只要 KPIList 变量保持为 List<string>。 .

谢谢

弗朗切斯科

最佳答案

如果可以并且不需要的话,你可以跳过匿名类

 lkpiTodisplay.Add("Business Target");

你可以做到

lkpiTodisplay.Select( x => x.KPI_Name).ToList();

获取List<String>

关于c# - 如何将 List<Anonymous Type> 转换为 List<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5720514/

相关文章:

c# - 整个查询的 lambda 中的 If 语句

.net - Entity Framework nvarchar外键区分大小写

c# - 将方法转换为 Linq 表达式以供查询

c# - 在 .NET 环境中使用 REST API 的最常见方法是什么? C#、JS 还是其他语言?

c# - 通过 API Microsoft Bot Framework 返回货币汇率

asynchronous - 使用任务并行库进行异步 I/O 的建议

visual-studio - Visual Studio 在调试 .NET 4.0 应用程序时使用 .NET 4.5 调试 fatal error 0x8007000e

c# - 静态元素的执行顺序初始化

c# - AutomationElement 如何用于 UI 自动化

linq-to-sql - 使用 LINQ 查询和基于两个参数的顺序连接两个表