简体   繁体   中英

How to change value of a property of a dynamic object in c#?

I call a stored procedure from my code and it returns a

 IEnumerable<dynamic> data 

with 3 properties

I would like to be able to modify one of a value of the data var for example

data[2].ID = 6687687

Do you know how to do this please?

You can access individual elements by using the ElementAt method like this:

data.ElementAt(2).ID = 6687687;

However, this is not efficient since it will iterate through the enumerable until it reaches the required index. And sometimes the enumerable that you get will execute some query every time your enumerate it. This means that you will get new objects every time you enumerate it (eg via ElementAt ).

A better way is to convert the enumerable to a list like this:

var list = data.ToList();

And then access the elements by index like this:

list[2].ID = 6687687;

You can use the following code:

var lItem = data.ElementAt(2);
lItem.ID = 6687687;

However note, that this can have a bad runtime performance when used to access many different indexes and the IEnumerable has no "simple" list object as a basis.

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