【问题标题】:C# How to unite two data types into a listC#如何将两种数据类型合并到一个列表中
【发布时间】:2021-09-18 22:51:44
【问题描述】:

我有一个简单的 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();

crudeInfoByMonth 是 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>'

【问题讨论】:

  • 您需要执行以下操作:List&lt;CleanByMonth&gt; cleanMonths = crudeInfoByMonth.Value.Select(x =&gt; new CleanByMonth { x.Year , x.Month, x.NumberOfUsers}).ToList();(给予或接受)。你不能只选择一个新的匿名对象,你必须创建新的CkeanByMonth 实例
  • @Flydog57 感谢您的帮助。但它仍然不起作用。我做了这样的事情:List&lt;CleanByMonth&gt; cleanMonths = crudeInfoByMonth.Value .Select(x =&gt; new CleanByMonth {x.Year , x.Month, x.NumberOfUsers}).ToList(); 在每个x.field 上都说无法解析符号“添加”

标签: c# list hierarchy


【解决方案1】:

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

【讨论】:

  • 感谢您的帮助。但它仍然不起作用。我做了这样的事情: List cleanMonths = roughInfoByMonth.Value .Select(x => new CleanByMonth {x.Year , x.Month, x.NumberOfUsers}).ToList();在每个 x.field 上都说无法解析符号“添加”
  • 这意味着您的代码有其他问题。用crudeInfoByMonth的详细信息更新问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
相关资源
最近更新 更多