Reputation: 2116
I've written this method to cast a comma separated string into a List of its type:
public List<T> GetListFromString<T>(string commaSplited)
{
return commaSplited.Split(',').Cast<T>().ToList();
}
But it throws an exception saying 'The specified cast is not valid.'
I've tested it with long input.
Upvotes: 0
Views: 3258
Reputation: 150108
Your code certainly works if T is string (I tested it).
If T is something else, say int, you will get this Exception.
This Works
List<string> result = GetListFromString<string>("abc, 123, hij");
This Fails
List<int> resultInt = GetListFromString<int>("23, 123, 2");
That is because one cannot cast or convert string to int, e.g. the following would fail too:
int three = (int)"3";
The Fix
public List<T> GetListFromString<T>(string commaSplited)
{
return (from e in commaSplited.Split(',')
select (T)Convert.ChangeType(e, typeof(T))).ToList();
}
However all of the given strings must be convertable to T, e.g. the following would still fail:
List<int> resultIntFail = GetListFromString<int>("23, abc, 2");
because "abc" cannot be converted to type int.
Also, T must be some type that System.Convert() knows how to convert to from a string.
Upvotes: 7