3

I get SonarCloud error in this code:

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.");
    }
}

My question is how to translate this code into LINQ using Select (as sonar suggest) when I have exceptions?

user16358371
  • 101
  • 1
  • 7

1 Answers1

6

I found the solution in order for sonar to be happy. :) But honestly it makes sense.

So, sometimes you can get the this error when you want to iterate through whole object but you just need one property, like in this situation. Here I want to iterate only through the names, so the solution will be:

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.");
    }
}
user16358371
  • 101
  • 1
  • 7