1

Array from Object

Looking at the above example I'm wondering how I can convert the requestedClass which is of type object into an array for me to read from.

    [HttpGet]
    public object Get(string table, string columns, int id)
    {
        var splitColumns = columns.Split(',');
        var t = new propertyModel()
        {
            gallery = _db.PROPERTYGALLERies.Where(p => p.propertyId == id).ToList(),
            property = _db.PROPERTies.SingleOrDefault(p => p.id == id)
        };

        var requestedClass = t.GetType().GetProperty(table.ToLower()).GetValue(t, null);
        var returnArray = new Dictionary<string, List<string>>();
        var requestArray = new List<string>();

        foreach (var column in splitColumns)
        {
            foreach (var field in StringProperties(requestedClass, column))
            {
                requestArray.Add(field.Value);
            }
        }

        returnArray.Add(table, requestArray);

        return Json(returnArray, JsonRequestBehavior.AllowGet);
    }

    public IEnumerable<KeyValuePair<string, string>> StringProperties(object obj, string column)
    {
        return from p in obj.GetType().GetProperties()
               where p.Name == column
               select new KeyValuePair<string, string>(p.Name, Convert.ToString(p.GetValue(obj)));
    }
12
  • Sorry for short question, trying to sort dinner for two little ones and also sort this issue out :D Commented Jun 2, 2016 at 17:32
  • Can you please show your code as a plain text, not as an image? Commented Jun 2, 2016 at 17:33
  • Yeah sure, two seconds Commented Jun 2, 2016 at 17:34
  • What is the value of requestedClass.GetType()? Commented Jun 2, 2016 at 17:34
  • 1
    @DangerZone I think it's still pertinent, if you don't still I can remove for sure. Just it shows the result of requestedClass Commented Jun 2, 2016 at 17:39

2 Answers 2

3

You can just cast it to whatever the proper underlying type is. If the object is actually, for instance, an instance of DataObject[] you can just do:

DataObject[] mydataObjectArray = (DataObject[])requestedClass;

And you should be all set. Keep in mind, DataObject is just a made up class I am using to illustrate the concept. Whatever requestedClass was originally before it was cast as an object is what you will need to cast it to.

Sign up to request clarification or add additional context in comments.

5 Comments

Problem I have is that I'm grabbing the object class dynamically. As far I can see atm there's no way of getting the data type into a variable to use in this way.
It depends on what you are wanting to do with it. You can use requestedClass.GetType() and use reflection for any number of things. Like I said though, it all depends on what you are wanting to do with it.
Let me create a video quick to show you my requirements... and issues
We don't need a video. Just describe what you are trying to achieve. Maybe include some pseudo-code as an example to provide some context.
Basically I'm trying to call a URL such as /{controller}/{action}/{table}/{fields}/{id} and the API to pass back the selected fields from selected table. It works perfectly for a SingleOrDefault() data type but when it's stored in an array I'm getting this issue of not being able to convert into something I can iterate through.
1

It depends on what you know about the object at compile-time. If all you know is that it's an IEnumerable<>, you should be able to cast it like this:

object[] values = ((IEnumerable<object>)requestedClass).ToArray();

If you also know that it always contains Data.PROPERTYGALLERY objects, you could cast the items to end up with a more strongly-typed array:

Data.PROPERTYGALLERY[] values = ((IEnumerable<object>)requestedClass)
    .Cast<Data.PROPERTYGALLERY>()
    .ToArray();

5 Comments

Unfortunately I don't know what object Class they'll be requesting. Basically I'm trying to call a URL such as /{controller}/{action}/{table}/{fields}/{id} and the API to pass back the selected fields from selected table. It works perfectly for a SingleOrDefault() data type but when it's stored in an array I'm getting this issue of not being able to convert into something I can iterate through.
This was actually so so close to the end result that I'm upvoting but can't push it as the correct answer. If you want to alter the answer slightly to read IEnumerable<object> collection = (IEnumerable<object>)requestedClass; and then it was a case of foreach on the collection. I'll mark it as the Answer.
@TheAngrySaxon: Let me know if my updated answer is sufficiently correct.
No, there's no need to convert toArray() as it was already seen as one. All that I needed to do was store each object array into an IEnumerable<object> I'm not even sure if I need to cast to an IEnumerable<object> as well TBH. The model class needed to be left ambiguous as it was being set during runtime.
@TheAngrySaxon: "Looking at the above example I'm wondering how I can convert the requestedClass which is of type object into an array for me to read from." The ToArray() ensures that it's an array. If you don't need an array, just omit that call.

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.