0

I am stuck with this line of the code.. with the following error message "type of conditional expression cannot be determined because there is no implicit conversion between int and string" on this c.TrackID and c.Times bit line of the code.

I tried using this (object) solution from here and this one too but none of theme worked.

What am I doing wrong here? Here's the code for your inspection:

Func<TopPlayed, string> orderingFunction = (c => sortColumnIndex == 1 && is_trackID_Sortable ? c.TrackID :
             sortColumnIndex == 2 && is_trackName_Sortable ? c.TrackName :
             sortColumnIndex == 3 && is_artistName_Sortable ? c.ArtistName :
             sortColumnIndex == 4 && is_times_Sortable ? c.Times : "");
Community
  • 1
  • 1

3 Answers3

0

The return types of the values returned by ternary statements must match one other. Tack a ToString() onto the one(s) that are not String:

c.TrackID.ToString()
DonBoitnott
  • 10,787
  • 6
  • 49
  • 68
0

The mistake here is that the Ternary Operator Must be able to determine the output by matching both the true ("?") and false ("*") results to a single common type. If it cannot make this match, the exception you see is thrown.

To solve the issue, make sure both results are the same type. For Int, simply append .ToString.

Func<TopPlayed, string> orderingFunction = (c => sortColumnIndex == 1 && is_trackID_Sortable ?
    c.TrackID.ToString() : // This will solve the Int/String conversion
    sortColumnIndex == 2 && is_trackName_Sortable ? c.TrackName :
    sortColumnIndex == 3 && is_artistName_Sortable ? c.ArtistName :
    sortColumnIndex == 4 && is_times_Sortable ? c.Times : 
    "");

In other cases, you may need to use explicit conversion, such as

...
? mySomeTypeObject
: (SomeType)null
David
  • 10,458
  • 1
  • 28
  • 40
0

if c.TrackId is an int, then you can't leave the last value as an empty string, you need to assing an int value too

Function = (c => (sortColumnIndex == 1 && is_trackID_Sortable) ? c.TrackID :
(sortColumnIndex == 2 && is_trackName_Sortable) ? c.TrackName :
(sortColumnIndex == 3 && is_artistName_Sortable) ? c.ArtistName :
(sortColumnIndex == 4 && is_times_Sortable) ? c.Times :0);

Also the use of parenthesys is a good idea

neiha
  • 171
  • 5