这是我的viewModel:
private AttachmentViewModel MapAttachmentViewModel(WorkOrderAttachment attachment)
{
var fileInfo = _fileService.GetFileInformation(attachment.FileLog);
return new AttachmentViewModel
{
Id = attachment.Id,
Exists = fileInfo.Exists,
FileExtension = fileInfo.Extension,
FileName = fileInfo.FileName,
Title = attachment.Title,
Description = attachment.Description,
UploadedBy = attachment.CreatedBy,
UploadedDate = attachment.DateCreated,
**Categories = attachment.CategoryMappings
.Select(x => x.WorkOrderAttachmentCategory)
.Select(x => x.Name)
.ToArray()**
};
}
示例:
对于类别,我需要返回类别的名称,但是如果返回空或null,我希望将其反之为“未分类”。
答案 0 :(得分:2)
您可以像这样使用DefaultIfEmpty:
Categories = attachment.CategoryMappings
.Select(x => x.WorkOrderAttachmentCategory)
.Select(x => x.Name).DefaultIfEmpty("uncategorized")
.ToArray()
这将处理if集合为null的情况(item没有“ CategoryMappings”)。但是,如果您的“ x.Name”为空字符串或空格,则还必须在“ Select(x => x.Name)”语句中注意以下内容:
Select(x => x.Name==null || x.Name==String.Empty?"uncategorized":x.Name)