简体   繁体   中英

How to convert C# object property values to N decimal array

I want to convert my object property values to array like this. (This list comes from database as object dynamically.)

  var myobject = List<object> {
    new { name="john", age=25 },
    new { name="bill", age=26 },
    new { name="scott", age=27 }
  }

When I send this object to user via asp.net web api, it return like this:

  [
    { name:"john", age:25 },
    { name:"bill", age:26 },
    { name:"scott", age:27 }
  ]

But I want to send my response as array like this:

  [
    ["john",  25 ],
    [ "bill", 26 ],
    [ "scott", 27 ]
  ]

My object properties may be change by request.

I need to create an N decimal array for my object proerty values. Is there any way to do this?

You have to use reflection if you don't know the names of the properties. For example:

var results = myobject.Select(o => 
    o.GetType()
        .GetProperties()
        .Select(p => p.GetValue(o)));

However, as a point to note, because you are not sending the name of the property along with the value, that would lead to some ambiguity. For example, if the object looked like this { age = 15, shoeSize = 10 } , you would be sending out [11, 10 ] . So the consuming service would need to explicitly know what was being sent back.

Edit: Here's a fiddle showing how it works: https://dotnetfiddle.net/iej1pO

您可以直接通过下一条指令进行转换:

  myobject.Select(o => new object[]{ o.name, o.age}).ToArray()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM