The problem is with operator precedence, forcing the compiler to parse the expression in a way you don't expect. Just wrapping the ternary expression in parens will politely explain to the compiler what you want to say.
As a side note, looking at the logic of an expression, I think the order of the terms of the result is incorrect. I have included them in the code below.
IEnumerable<SelectListItem> items = contacts .Select(r => new SelectListItem() { Value = r.ContactID.ToString(), Text = r.FirstName + " " + (string.IsNullOrEmpty(r.MiddleInit) ? "" : r.MiddleInit + ". ") + r.LastName });
Additional Information
Without ( , + has a higher priority than ?: So the expression in your question is parsed as if it were saying:
Test = (r.FirstName + " " + string.IsNullOrEmpty(r.MiddleInit)) ? (r.MiddleInit + ". ") : ("" + r.LastName)
So, the source of your error is that the conditional part of the ?: Statement is actually a string that will contain something like "Andrew true". Also note that r.LastName combined with the third member of the ?: Operator.
Question Trim ()
If it is likely that r.MiddleInit may contain spaces, then using Trim() will help, but it would be better to change the test to String.IsNullOrWhiteSpace(r.MiddleInit) .
source share