Click here to Skip to main content
15,881,812 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Unknown size Numeric Arrays from Strings - dontumindit

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
14 Feb 2011CPOL 4.6K   2  
I prefer something a little more generic:public static IEnumerable Convert(string value, char separator) where TTypeConverter : TypeConverter { var typeConverter = (TTypeConverter)TypeDescriptor.GetConverter(typeof(TValue)); ...
I prefer something a little more generic:

C#
public static IEnumerable<TValue> Convert<TValue, TTypeConverter>(string value, char separator) where TTypeConverter : TypeConverter
       {
           var typeConverter = (TTypeConverter)TypeDescriptor.GetConverter(typeof(TValue));
          return new List<string>(value.Split(separator))
              .ConvertAll<TValue>(s => (TValue)typeConverter.ConvertFrom(s));
       }


That way I can convert a delimited string to a large number of IEnumerable<T> collections in just one line and I don't have to worry about the size of the collection either:

C#
public static void UsageMethod()
        {
            var myIntegers = ((List<int>)Convert<int, TypeConverter>("1,2,3,4,5", ',')).ToArray();
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
First batch file in 1987

Messed around with the Bullfrog C++ Libraries for Syndicate in 1994

Web Developer since 2000

.net Developer since 2001

MCTS: Microsoft® .NET Framework 2.0 - Web-based Client Development

MCTS: Web Applications Development with Microsoft .NET Framework 4

Comments and Discussions

 
-- There are no messages in this forum --