c# - 应通过调用 Select 来简化循环 - sonar cloud error c#

标签 c# .net sonarcloud

我在这段代码中收到 SonarCloud 错误:

foreach (var item in itemList)
{
    if (string.IsNullOrEmpty(item.Name))
    {
        throw new BadRequestException("Item name is null or missing...");
    }
    if (someOtherList.Any(x => x.Name == item.Name))
    {
        throw new NotAcceptedException("Item name already exist in Db.");
    }
}

我的问题是,当我遇到异常时,如何使用Select(如声纳建议的那样)将此代码转换为LINQ

最佳答案

我找到了让声纳快乐的解决方案。 :) 但老实说这是有道理的。

因此,有时当您想遍历整个对象但只需要一个属性时,您可能会遇到此错误,就像在这种情况下一样。这里我只想遍历名称,所以解决方案是:

foreach (var itemName in itemList.Select(x => x.Name))
{
    if (string.IsNullOrEmpty(itemName))
    {
        throw new BadRequestException("Item name is null or missing...");
    }
    if (someOtherList.Any(x => x.Name == itemName))
    {
        throw new NotAcceptedException("Item name already exist in Db.");
    }
}

关于c# - 应通过调用 Select 来简化循环 - sonar cloud error c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71157634/

相关文章:

jenkins - 如何将 SonarCloud 与 GitHub 和 Jenkins 集成

c# - 如何在C#中去除URL中的www、http/https等字符串

c# - 枚举上的 IEnumerable 扩展方法

c# - Monogame child 更新方法滞后

c# - 'External table is not in the expected format' 异常问题

c# - 什么是 '=>' ? (C#语法题)

c# - Caliburn 对模型-对象的微 Action

c# - 使用 Console.WriteLine (C#) 或 printfn (F#) 编写粗体文本?

java - 如何配置 SonarCloud

java - 使用 SLF4J 记录异常时,Sonarcloud 会发出警报 "not enough arguments"