如何手动将对象列表映射到DTO列表?

时间:2019-06-29 01:31:35

标签: c# asp.net-mvc linq

我有这些:

public class FamilyHead
{
    public Guid HeadId { get; set; }
    public string Name { get; set; }
}

public class Citizen
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public short Age { get; set; }
    // more properties
    [ForeignKey("FamilyHead")]
    public Guid HeadId { get; set; }

    public virtual FamilyHead FamilyHead { get; set; }
}

public class CitizenDTO
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public short Age { get; set; }
    public Guid HeadId
    public string HeadName { get; set; }
}

如果是单个实例,我可以通过扩展方法手动将其映射:

public static CitizenDTO ToDTO(this Citizen citizen)
{
    if (citizen == null) return null;

    return new CitizenDTO {
        Id = citizen.Id,
        Name = citizen.Name,
        HeadId = citizen.HeadId,
        HeadName = citizen.FamilyHead.Name
    }   
}

var dto = aCitizen.ToDTO();

但是如何绘制公民名单?我认为Select()可以完成这项工作,但我只知道如果模型和dto具有相同的结构,该怎么做。像这个例子:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());

那么如何映射它的列表?

2 个答案:

答案 0 :(得分:2)

您可以像在问题中使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <ol id="myUL"> <li>Hello 1</li> <li>Hello 2 <ol></ol> </li> <li>Hello 3 <ol> <li>Hello 3.1</li> <li>Hello 3.2</li> <li>Hello 3.3</li> </ol> </li> </ol>一样使用Linq origdict = { 'b': 66, 'b': 68, 'c': 68, 'x': 68, 'z': 401, 'aa':401, 'a': 2} my_list = [] my_dict = {} for index, (key, value) in enumerate(origdict.items()): if value in my_dict: my_dict[value].append(key) else: #validate is not first index of list if index > 0: my_list.append(my_dict) my_dict = {} my_dict[value] = [key] #validate last index of list if index == len(origdict)-1: my_list.append(my_dict) print(my_list) ,而无需编写长扩展方法

[{68: ['b', 'c', 'x']}, {401: ['z', 'aa']}, {2: ['a']}]

答案 1 :(得分:0)

我在完成问题之前就找到了答案。只需遍历列表,然后将映射的DTO添加到该列表即可。愚蠢的我

// Extension method
public static IEnumerable<CitizenDTO> ToDTO(this IEnumerable<Citizen> citizens)
{
    if (citizen == null) return null;

    var dto = new List<CitizenDTO>();

    foreach(var citizen in citizens) {
        dto.Add(citizen.ToDTO());   
    }

    return dto;
}

// How to use
IEnumerable<CitizenDTO> result = listOfCitizens.ToDTO();