首页 > 解决方案 > 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>'

标签: c#listhierarchy

解决方案


匿名类型也是一种类型,就像你的一样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();

推荐阅读