简体   繁体   中英

How to do pretty block of code with Arrays and DTO in C#?

I recently switched to C# after NodeJS, I am interested in the question, is it possible to beautifully and correctly format a block of this code, to reduce unnecessarily?

var user = userService.GetById(id);
if (user == null)
    return null;

var roles = new List<RoleDTO>();
foreach (var u in user.Roles)
{
    roles.Add(new RoleDTO
    {
        Id = u.Role.Id,
        Name = u.Role.Name,
        Slug = u.Role.Slug
    });
}

return new UserDTO
{
    Id = user.Id,
    Login = user.Login,
    Name = user.Name,
    Roles = roles
};

Your code is IMHO already quite short. The only additional thing I can think of is replacing the foreach with a LINQ exprssion in the constructor of List<RoleDTO> and not use a variable for it, like so:

var user = userService.GetById(id);
if (user == null)
    return null;

return new UserDTO
{
    Id = user.Id,
    Login = user.Login,
    Name = user.Name,
    Roles = new List<RoleDTO>
    (
        from u in user.Roles
        select new RoleDTO
        {
            Id = u.Role.Id,
            Name = u.Role.Name,
            Slug = u.Role.Slug
        }
    )
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM