mardi 30 août 2022

c# Iterate over var with value obtained with GetValue()

In an MVC 5 c# application, I am attempting to extract values from objects at runtime using strings for property names. The process works fine until the value extracted is a collection. I am unable to write the code to iterate over the extracted value.

using System;
using System.Collections.Generic;               
public class Program
{
    public static void Main()
    {
        Student student = new Student { 
             Lectures = new List<Lecture>{ 
                new Lecture { Title="Science"},
                new Lecture {Title="Math"}
             }
        };
        
        var obj = student;
        string fld = "Lectures";

        // The following code knows nothing about Students or Lectures
        // It does know that the "fld" is a property name of "obj" that contains a collection

        var items = obj.GetType().GetProperty(fld).GetValue(obj);
        foreach (var item in items)
        {
            // Code to process item
        }
    }
}

public class Lecture
{
     public string Title {get;set;}
}

public class Student
{
   public List<Lecture> Lectures {get;set;}
}

The above "for" instruction is flagged as a syntax error with the red highlight on "items". The error indicates that it cannot operate on variables of type "object" because "object" does not contain a public definition for GetEnumerator.

Pasting the above code into https://dotnetfiddle.net illustrates the issue.

Is what I attempting possible? When debugging, "items" does show as a collection of Lecture.





Aucun commentaire:

Enregistrer un commentaire