【问题标题】:LINQ - For each item in select populate value to one unpopulated propertyLINQ - 对于选择中的每个项目,将值填充到一个未填充的属性
【发布时间】:2019-10-06 10:17:15
【问题描述】:

我正在使用我的Map 方法从我的上下文类Company 创建DTO 对象,并且映射如下所示:

private CompDTO Map(Company company)
{
    return new CompDTO()
    {
        Id = company.Id,
        Title = company.Title,
        ParentCompanyId = company.ParentCompanyId,
    };
} 

CompDTO 看起来像这样:

public class CompDTO
{
    public long Id { get; set; }
    public string Title { get; set; }
    public long? ParentCompanyId { get; set; }
    public bool HasChildrens { get; set; }
}

这是我调用 Map 方法的方式:

private IEnumerable<CompDTO> Map(IEnumerable<Company> companies)
{

    var result = companies.Select(c => Map(c));

     return result.Select(c => { c.HasChildrens = companies.Any(cc => cc.ParentCompanyId == c.Id)});
 }

在主映射之后,我尝试在我的return result.Select 中为每个compDTO 项目填充HasChildrens 属性。

但它不起作用,因为它说:

但我想还有更深层次的问题,因为我添加了这样的简单测试:

return result.Select(c => { c.HasChildrens = true; }); 

它说:方法的类型参数不能从用法中推断出来。

任何形式的帮助都会很棒

【问题讨论】:

  • 请避免两次或更多次发布相同的问题。
  • @OlivierRogier 之前的问题已被删除..
  • 好的,但除非你有真正的理由,否则你可以编辑它。
  • @OlivierRogier 我删除了之前的问题,因为它非常相似,这是现在唯一的问题

标签: c# linq linq-to-entities ienumerable


【解决方案1】:

IEnumerable Select 应该从输入创建一个新序列。如果您只想使用 Select 更改属性,因为它是一个 foreach,那么您需要返回传递给您的 lambda 的对象

 return result.Select(c => 
               { 
                   c.HasChildrens = companies.Any(cc => cc.ParentCompanyId == c.Id);
                   return c;
               });

但是你真的更喜欢这种方法而不是简单的 For 循环吗?我觉得这更清楚

foreach(Company c in result)
    c.HasChildrens = companies.Any(cc => cc.ParentCompanyId == c.Id);

return result;

【讨论】:

  • 先生,添加此内容后怎么可能会显示 $exception{"A command is already in progress: SELECT t.id,name, etc, etc FROM companies AS c\r\n etc. etc Npgsql.NpgsqlOperationInProgressException .. 我的意思是,我们怎么不会再访问上下文了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-23
  • 1970-01-01
  • 2014-12-10
  • 2020-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多