none
string to object Array RRS feed

  • Question

  • var param = (new object[] { 124, "123", "TEST" }); //This returns correct array of objects with first is integer and other two are strings.

    But I have this parameter values in string as below and want to convert to  var param same as above.

    string Query = "123, \"123\", \"TEST\"";

    I tried below solutions but everything i s returned as string, how can I split into object instead of string

    object[] obj = Query.Replace("\"", "").Split(',');

    Wednesday, September 5, 2018 7:11 PM

Answers

  • In simplest case, when substrings do not contain ‘,” nor ‘”’, try this:

    object[] obj = 
        Query
            .Split( ',' )
            .Select( s => s.Trim() )
            .Select( s => s.StartsWith( "\"" ) ? (object)s.Trim( '"' ) : int.Parse( s ) )
            .ToArray();
    


    • Marked as answer by Rups1 Wednesday, September 5, 2018 8:24 PM
    Wednesday, September 5, 2018 7:50 PM