0

I'm trying to convert a HttpRequest.QueryString to object[] with this extension method:

public static object[] ToObjectArray(this NameValueCollection nvc)
{
    var ret = new object[nvc.Count];

    var count = 0;
    foreach (string s in nvc)
    {
        var strings = nvc.GetValues(s);
        if (strings != null)
        {
            foreach (string v in strings)
            {
                ret[count] = new { s = v };
            }
        }
        count++;
    }

    return ret;
}

var args = request.QueryString.ToObjectArray();

I think that I'm pretty close, but I'm getting the following exception:

Object of type '<>f__AnonymousType0`1[System.String]' 
cannot be converted to type 'System.Object[]'.

What did I miss?

1 Answer 1

1

You don't need to convert v to a new object, a string is already an object, so you can just do:

ret[count] = v;

Here's a slightly shorter way, using a list to avoid having to keep up with the array index.

public static object[] ToObjectArray(this NameValueCollection nvc) {
    List<object> results = new List<object>();
    foreach (string key in nvc.Keys) {
        results.Add(nvc.GetValues(key));
    }
    return results.ToArray();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I ended up with return (from string key in nvc.Keys select nvc.GetValues(key)).Cast<object>().ToArray();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.