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

问题描述 投票:0回答:1

我正在尝试通过以下一种ASP.NET MVC方法返回JSON结果:

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,则“消息”将包含一个空字符串。

示例,可能的情况:

  1. 当resp为空字符串或NULL =>消息将为空字符串
  2. 当resp不为空/空时,示例:
    • {“错误”,“ blabla”},{“ warn”,NULL} =>消息将为“ blabla”
    • {“ errors”,“ blabla”},{“ errors”,“ blablabla”},{“ warn”,NULL} =>消息将为“ blabla; blablabla”
    • {“错误”,NULL},{“警告”,NULL} =>消息将为空字符串

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

c# asp.net asp.net-mvc lambda linq-expressions
1个回答
0
投票

通常,我们不必担心空列表或字典,但是空值需要一些额外的检查。您还具有一个集合的集合,因此可以展平以便可以使用SelectMany。

© www.soinside.com 2019 - 2024. All rights reserved.