简体   繁体   中英

Type of conditional expression cannot be determined because there is no implicit conversion between 'int?' and 'string'

I have this line of code :

Ages = m.RelatedMultipleWorks.Count == 0 ? 
       m.RelatedLook.Age: m.RelatedLook.Age.ToString() + " | " +
                          m.RelatedMultipleWorks.
                            Select(z => z.RelatedLook.Age.ToString()).
                            Aggregate((current, next) => current + " | " + next)

This whole line is giving this error :

Type of conditional expression cannot be determined because there is no implicit conversion between 'int?' and 'string' 

I can't understand why I'm getting this error. How can I get rid of it? Thanks.

Your m.RelatedLook.Age is presumably an int? , but the result of the secondary ternary expression is a string due to .Aggregate .

Ages (presumably) expects an int? ; the second half of the ternary cannot be implicitly converted to int? , so the compiler yells at you. This is assuming that .Ages is a int? , otherwise you should .ToString() the result of checking m.RelatedLook.Age .

Sounds kinda smelly to be storing Ages as a string, though - consider maybe using IEnumerable<int> instead?

I originally approached this answer trying to explain that perhaps the Ages type was incorrect, but I should explain that this is occurring because the ternary cannot resolve to both string and int? because those types are not equivalent. Just ToString ing the first age would fix the compiler error.

Ternary operator expects both outputs to be of same type. Use the following:

Ages = m.RelatedMultipleWorks.Count == 0 ? m.RelatedLook.Age.ToString(): m.RelatedLook.Age.ToString() + " | " + m.RelatedMultipleWorks.Select(z => z.RelatedLook.Age.ToString()).Aggregate((current, next) => current + " | " + next),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM