samedi 17 août 2019

How to access custom list object at runtime

I have the following custom object

public class Events
{
    public int Id { get; set; }
    public DateTime CreateDate { get; set; }
    public string Category { get; set; }
}

It is stored serialized as a List<Events>

[
  {
    "Id": 1,
    "CreateDate": "2019-08-15",
    "Category": "consert"
  },
  {
    "Id": 2,
    "CreateDate": "2019-08-15",
    "Category": "movie"
  },
  {
    "Id": 3,
    "CreateDate": "2019-08-15",
    "Category": "dance"
  }
]

Read/deserialized, using typed variable and linq to access properties/values

List<Events> eventlist = JsonConvert.DeserializeObject<List<Events>>(jsonstring)

var maxid = eventlist.Max(i => i.Id);


I started testing how to use reflection to access an events properties/values.

foreach (var pi in eventlist[0].GetType().GetProperties())
{
    if (pi.CanWrite && pi.CanRead)
    {
        object o = pi.GetValue(itemData, null);
        if (o != null)
        {
            ...
        }
    }
}


If I now also would read/deserialized at runtime, e.g.

var eventlist = JsonConvert.DeserializeObject(jsonstring, eventtype)


How do I, using reflection, get the runtime-created eventlist items, and e.g. find the max id?





Aucun commentaire:

Enregistrer un commentaire