【发布时间】:2020-07-29 19:46:35
【问题描述】:
我有一本 Dictionary<string, (int Id, string Code, string Name)> 类型的字典:
var dict = new Dictionary<string, (int Id, string Code, string Name)>
{
["subjectType"] = (1, "1Code", "1Name"),
["residentType"] = (2, "2Code", "2Name"),
["businessType"] = (3, "3Code", "3Name"),
// and so on...
};
我在这里使用元组(int Id, string Code, string Name),但我可以用一个类来替换它。所以,元组或类都没有关系,我只需要为每个字典项设置三个属性(Id、Code、Name)。
我需要将这个字典投影到一个类中,所以我像这样分别映射输出模型的每个属性:
public static OutputModel Map(
Dictionary<string, (int Id, string Code, string Name)> dictionary) =>
new OutputModel
{
SubjectTypeId = dictionary["subjectType"].Id,
SubjectTypeCode = dictionary["subjectType"].Code,
SubjectTypeName = dictionary["subjectType"].Name,
ResidentTypeId = dictionary["residentType"].Id,
ResidentTypeCode = dictionary["residentType"].Code,
ResidentTypeName = dictionary["residentType"].Name,
BusinessTypeId = dictionary["businessType"].Id,
BusinessTypeCode = dictionary["businessType"].Code,
BusinessTypeName = dictionary["businessType"].Name,
// and so on...
};
我想知道有没有其他(更花哨的)方法来做同样的映射?
【问题讨论】:
-
我喜欢使用 Linq。从以下帖子中查看我的答案:stackoverflow.com/questions/61248657/…
标签: c# dictionary tuples mapping