如果数组使用linq查询返回空,则需要插入一个字符串

时间:2019-04-03 20:03:28

标签: asp.net-mvc linq

这是我的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,我希望将其反之为“未分类”。

1 个答案:

答案 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)