LINQ-对于选择的每个项目,将值填充为一个未填充的属性 [英] LINQ - For each item in select populate value to one unpopulated property

查看:101
本文介绍了LINQ-对于选择的每个项目,将值填充为一个未填充的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using my Map method to create DTO object from my context class Company and Mapping looks like this:

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方法的方式:

Here's how I'm calling my Map method :

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)});
 }

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

After main mapping I'm trying to populate HasChildrens property in my return result.Select for each compDTO item.

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

But it doesn't work cuz it says:

但是我想还有一个更深层次的问题,因为我只是添加了这样的测试:

But I guess there's more deeper issue because I added simply test like this:

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

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

任何一种帮助都很棒

推荐答案

IEnumerable Select应该从输入中创建一个新序列.如果您只想使用Select作为一个foreach来更改属性,则需要返回传递给lambda的对象

The IEnumerable Select is supposed to create a new sequence from the input. If you want to just change a property using Select as it were a foreach then you need to return the object passed to your lambda

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

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

But do you really prefer this approach to a simple For Loop? I find this more clear

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

return result;

这篇关于LINQ-对于选择的每个项目,将值填充为一个未填充的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆