如何从视图模型中的字符串列表构建字符串?

时间:2018-11-30 10:43:43

标签: c# asp.net-core-mvc

我的视图模型具有以下属性:

public string FullInfo => LastName + ", " + FirstName
    + " (" + string.Join(",",EmployeeRoles) + ")";
public List<EmployeeRoleViewModel> EmployeeRoles { get; set; }

...产生以下输出:

  

Doe,约翰({项目名称} .Models.EmployeeRoleViewModel,{项目名称} .Models.EmployeeRoleViewModel)

我正在寻找的输出是这样:

  

Doe,John(高级经理助理经理)

string.Join的最后一位没有执行我想要的操作。我想添加一个TitleEmployeeRoles的逗号分隔列表,如下所示:

public class EmployeeRoleViewModel
{
    public int RoleId { get; set; }
    public string Title { get; set; }
    public bool Selected { get; set; }
}

如何实现?

2 个答案:

答案 0 :(得分:1)

您应该定位Title对象的EmployeeRoles属性

public string FullInfo => LastName + ", " + FirstName
+ " (" + string.Join(",",EmployeeRoles.Where(r => r.Selected).Select(r => r.Title ).ToArray()) + ")";

答案 1 :(得分:1)

EmployeeRoles是一个类,.ToString()不是您想要的。您必须选择它的标题:

public string FullInfo => LastName + ", " + FirstName
    + " (" + string.Join(",",EmployeeRoles.Select(er => er.Title)) + ")";