0

how to convert dynamic variable to specific class. dynamic variable has the same properties as my specific class.

public class PracovnikHmotZodpovednostDropDownListItem
    {
        [Column("ZAZNAM_ID")]
        public int? ZaznamId { get; set; }
        [Column("TEXT")]
        public string Text { get; set; }
        [Column("VALL")]
        public int Value { get; set; }
        public bool Disabled { get; set; } = false;
        public UpdateStatusEnum UpdateStatus { get; set; }

    }

void someMethod(dynamic dtos){
List<PracovnikHmotZodpovednostDropDownListItem> dto =
 (List<PracovnikHmotZodpovednostDropDownListItem>)dtos;

}
SonDy
  • 49
  • 5
  • You might find this question useful https://stackoverflow.com/questions/17101190/is-there-a-way-to-convert-a-dynamic-or-anonymous-object-to-a-strongly-typed-dec – Kevin Oct 19 '20 at 14:03

1 Answers1

0

If all you know is that the properties have the same names, you're in duck typing territory, casting won't help you.

Good news is, it's trivial to do, just tedious:

var dtoList = new List<PracovnikHmotZodpovednostDropDownListItem>();
foreach(var dto in dtos)
    dtoList.Add(new()
    {
        ZaznamId = dto.ZaznamId,
        Text = dto.Text,
        // etc..
    });
Blindy
  • 65,249
  • 10
  • 91
  • 131