LINQ - For each item in select populate value to one unpopulated property

主宰稳场 提交于 2020-02-08 10:46:31

问题


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 looks like this:

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

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

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

And it said:The type arguments for method cannot be infered from usage.

Any kind of help would be awesome


回答1:


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

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;


来源:https://stackoverflow.com/questions/58256287/linq-for-each-item-in-select-populate-value-to-one-unpopulated-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!