Search code examples
c#linqlinq-to-entitiesienumerable

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


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: enter image description here

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


Solution

  • 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;