c# - C#如何将两种数据类型合并到一个列表中
问题描述
我有一个简单的 RegistrationCountByMonth 表
public int RegistrationCountByMonthId { get; set; }
public short? Year { get; set; }
public byte? Month { get; set; }
public int? NumberOfUsers { get; set; }
public virtual Month MonthNavigation { get; set; }
还有一个简单的 CleanByMonth 类型。我应该返回
public short? Year { get; set; }
public byte? Month { get; set; }
public int? NumberOfUsers { get; set; }
为什么我不能做类似的事情:
List<CleanByMonth> cleanMonths = crudeInfoByMonth.Value.Select(x => new { x.Year , x.Month, x.NumberOfUsers}).ToList();
rawInfoByMonth 是 RegistrationCountByMonth 类型。
我得到了这个错误......
Cannot convert source type '
System.Collections.Generic.List<{
System.Nullable<short> Year,
System.Nullable<byte> Month,
System.Nullable<int> NumberOfUsers}>'
to target type 'System.Collections.Generic.List<Server.ViewModel.CleanByMonth>'
解决方案
匿名类型也是一种类型,就像你的一样CleanByMonth
,所以你不能只是转换它。声明变量,var
以便它可以被识别为匿名。
var cleanMonths = crudeInfoByMonth.Value.Select(x => new { x.Year , x.Month, x.NumberOfUsers}).ToList();
但是,如果您仍希望将其作为 列表CleanByMonth
,则可以像这样将行之间的匿名替换为按月清洁的实际类型。
List<CleanByMonth> cleanMonths = crudeInfoByMonth.Value.
Select(x => new CleanByMonth { x.Year , x.Month, x.NumberOfUsers}).ToList();
推荐阅读
- eclipse - Scala Eclipse 项目 - 无法从资源目录中读取文本文件
- maven - 如何使用 tomcat8-maven-plugin 指定另一个项目中内置的 WAR 进行集成测试?
- java - 两个日期之间的春季启动方法不起作用
- apache-spark - 有没有办法使用特定的批量大小写入数据库?
- reactjs - 背景图像未显示在服务器(生产)生成的pdf中
- embedded - PyOCD 在我的 NuMaker 板上找不到 Nu-Link2-Me 探针
- sql - Postgres 中的索引
- python - 在全息视图(或 hvplot)中带有标记的线图
- php - 如何在 php 和 mysql 中进行乘法运算
- typescript - TypeScript 中枚举类型的可分配性规则是什么?