使用 lambda 表达式连接没有 NULL 值的字符串

Joining string with no NULL values using lambda expression

我正在尝试 return JSON 结果是我的 ASP.NET MVC 方法之一,如下所示:

Dictionary<string, List<System.ComponentModel.DataAnnotations.ValidationResult>> resp = 
    MyMethod(params);

return Json(new 
{ 
    result = res, 
    message = string.Join(";", resp.Select(v => v.Value.First().ErrorMessage))
}, JsonRequestBehavior.AllowGet);

resp 字典可能为空也可能不是。 resp 也可以是 null。当它不为空且不为 null 时,键值对可以包含 null 作为值,例如key="errors" 但其对应的值设置为 null。因此,考虑到这一点,我希望 message 字段包含一个以分号分隔的列表,其中包含所有非 null 字典值。如果 resp 为空,null,或者所有字典值都是 null,"message" 将包含一个空字符串。

示例,可能的场景:

  1. 当 resp 为空字符串或 NULL => 消息将为空 字符串
  2. 当 resp 不是 empty/null 时,示例:
    • {"errors","blabla"},{"warn",NULL} => 消息将是 "blabla"
    • {"errors","blabla"},{"errors","blablabla"},{"warn",NULL} => 消息将是 "blabla;blablabla"
    • {"errors",NULL},{"warn",NULL} => 消息将为空字符串

如何使用 lambda 表达式来获得这些结果?

一般来说,我们不需要担心空列表或字典,但空值需要一些额外的检查。你还有一个集合的集合,所以要展平你可以使用 SelectMany。

只需专注于获取消息,您不需要在一行代码中完成所有这些。

   var message = resp==null ? "" : string.Join(";", 
    resp.Where(l => l.Value != null)
        .SelectMany( l=> 
          l.Value.Where(vr => vr != null && !String.IsNullOrEmpty(vr.ErrorMessage))
           .Select( vr => vr.ErrorMessage )));

这应该会给您消息。抱歉,我没有编译 运行 它,但它应该具有您需要的所有 null 检查和扁平化。

您可以直接使用 resValues 属性(即 List<ValidationResult>),您可以简单地 select 所有那些ErrorMessage 不为 null 或为空:

return Json(new
{
    result = res,
    message = resp == null ? string.Empty : string.Join(";", 
        resp.Values.SelectMany(value => value
            .Where(validationResult => !string.IsNullOrEmpty(validationResult?.ErrorMessage))
            .Select(validationResult => validationResult.ErrorMessage)))
}, JsonRequestBehavior.AllowGet);