简体   繁体   中英

Concatenate object's properties of variable length of a C# object into a new property of the object

Having this problem solved in JavaScript, I'm trying to do the same using C# for a C# object, not a JSON.

Basically, the JS solving looks like this:

myObject.myObject.forEach(arr => {
 arr.prop = arr.parameters.reduce((res,obj)=> res+obj.special, '')
})

so I tried to do it like:

foreach (array arr in myObject.myObject)
{
    arr.prop = arr.parameters.reduce();
}

I didn't find any function like the JS reduce in C#.

Do you have any suggestions how to solve this?

You could do this by first getting all fields or Properties from an object via Reflection

var fields = myObject.GetType().GetFields();

then you pull all current values from those fields and make strings of it

var values = fields.Select(e => e.GetValue(myObject)?.ToString());

and after that, just aggregate the values

var allFieldsInOne = values.Aggregate((e,f) => e + f);

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