Not only is this difficult to read, it's also inefficient.
Cache your duplicate LINQ lookup to save time and make it more readable.
As for using the ternary operator, that's up to you, but I prefer to use a full if statement when the line gets too long.
Additionally swap out "" for String.Empty, it shows your intent better, and also makes it more strongly contrast against " "
var state =ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName));
if(state.Value != null &&
state.Value.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage)))
{
return string.Empty;
}
else
{
return " ";
}
I'm assuming this next bit executes elsewhere, because the two return statements above would otherwise make this unreachable code.
Use var when the type is obvious from the right hand side of the assignment (although in this case it's a little debatable, I'd personally use var here because the variable name mimics the type).
You have a typo in your second comment.
//Looks in a dictionary for a key called parameterName
var modelState = ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)).Value;
//If I could find it I look for any error associated to that and I return it as a single string
if(modelState.Value != null &&
modelState.Value.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage)))
{
return string.Empty;
}
else
{
return " ";
}
Finally, structure-wise I'd recommend converting the if-statement above into a separate method, since you call it in multiple places. This will leave a single point to modify during refactoring.
private string ConvertModelStateErrorsToString(ModelState modelState)
{
if(modelState.Value != null &&
modelState.Value.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage)))
{
return string.Empty;
}
else
{
return " ";
}
}
Leaving your other code samples as:
var state =ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName));
return ConvertModelStateErrorsToString(state);
And the other sample:
//Looks in a dictionary for a key called parameterName
var modelState = ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)).Value;
//If I could find it I look for any error associated to that and I return it as a single string
return ConvertModelStateErrorsToString(modelState);