I was able to convert comma separated string to an IList<int>
but how can I modify the same to get IList<T>
where T will be passed as one of the input parameter?
i.e if I need IList<int>
I will pass "int" as parameter, if I need IList<string>
I will pass "string" as parameter.
My idea is to get the type whether it is int or string through input parameter and use reflection and convert the string to respective list
Code to convert comma separated string as IList<int>
public static IList<int> SplitStringUsing(this string source, string seperator =",")
{
return source.Split(Convert.ToChar(seperator))
.Select(x => x.Trim())
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(int.Parse).ToList();
}
Note: Above code isn't tested yet
I am looking for something like
public static IList<T> SplitStringUsing(this string source, string seperator =",", T t)
{
find the type of t and convert it to respective List
}
I think you need Convert.ChangeType, like this. Its not fully tested, compile and fix.
You can use Convert.ChangeType(object,string) for parsing to the base types supported by the System.Convert class, or any other class that implements the IConvertible interface
To avoid localization issues, you should probably add an IFormatProvider parameter as well, to allow the caller to specify the culture to use or default to the current culture, eg:
For a more generic case, you can pass the parsing code as a lambda to the function:
and call it like this:
You can have both methods in your code and the compiler will pick the correct overload.
I would like to extend the answer of @PanagiotisKanavos.
Especially the generic approach with:
You would use that code:
You can add convenience implementations for all your String to T cases. If you don't want exceptions to be thrown just implement a parse function using Int32.TryParse, etc.