Reason of this exception?
Firstly, let's try this:
byte myByte = 11;
object myObject = myByte;
int x = (int)myObject; // Exception will be thrown here
As you see, InvalidCastException will be thrown. Because, a boxed value can only be unboxed to a variable of the exact same type.
Now, let's see what is Cast() doing. You can look at the implementation of this method here. As you see, it will return CastIterator. And here is the implementation of the CastIterator:
static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source)
{
foreach (object obj in source) yield return (TResult)obj;
}
As you see, it doesn't cast byte to int, but object to int. The reason of this is that, Cast is an extension method for IEnumerable, not IEnumerable<T>.
public static IEnumerable<TResult> Cast<TResult>(
this IEnumerable source
)
So use one of these ways:
var tmpMarketRights = AllMarketRights.Select(x => Convert.ToInt32(x)).ToList();
var tmpMarketRights = AllMarketRights.Select(x => (int)x).ToList();