简体   繁体   English

如何将C#对象属性值转换为N个十进制数组

[英]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: 当我通过asp.net网络api将这个对象发送给用户时,它返回如下:

  [
    { 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. 我需要为我的对象属性值创建一个N十进制数​​组。 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 ] . 例如,如果对象看起来像这样{ age = 15, shoeSize = 10 } ,则您将发送[11, 10 ] { age = 15, shoeSize = 10 } [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 编辑:这是显示其工作方式的小提琴: https : //dotnetfiddle.net/iej1pO

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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