简体   繁体   中英

IQueryable List<DTO> conversion

I need to fill an IQueryable of UserDTO with a List of TeamsDTO without a foreach-loop or materializing the data.

I have the following classes:

public class User
{
    public int Id {get;set;}
    public string Name {get;set;}
    public List<Team> Teams {get;set;}
}

public class Team
{
    public int Id {get;set;}
    public string Teamname {get;set;}
    public string Description {get;set;}
}

And the following DTOs:

public class UserDTO
{
    public int Id {get;set;}
    public List<TeamDTO> TeamsDTOList{get;set;}
}

public class TeamDTO
{
    public int Id {get;set;}
    public string Teamname {get;set;}
}

And the Code so far:

public static IQueryable<UserDTO> GetQueryableUserDTO(IQueryable<User> query)
        {
            var retQueryable = Enumerable.Empty<UserDTO>().AsQueryable();
            try
            {
                retQueryable = query.AsEnumerable()
                                .Select(k => new UserDTO
                                {
                                    Id = k.Id,
                                    TeamsDTOList= new List<TeamDTO>()
                                    {
                                        //Can't figure out this part
                                    }
                                });
            }
            catch (Exception ex)
            {
                BaseManager.Write2Log(ex);
            }
            return retQueryable;
        }

Thanks for the help in advance.

PS: Classes/code are of course a simplified example.

What about this:

retQueryable = query.AsEnumerable().Select(k => new UserDTO()
                {
                    Id = k.Id,
                    TeamsDTOList = k.Teams.Select(t => new TeamDTO(){ Id = t.Id, Teamname = t.Teamname}).ToList()
                });

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