IEnumerable to Object?

c# entity-framework-6

Question

I'm a little confused on how exactly this works. I have an IEnumerable<T> List that I'm pulling from a stored procedure in a mySQL database.

       IEnumerable<CheckInVar> CheckInVars = context.Database.SqlQuery<CheckInVar>(
          "Call getCheckinVars(\"WEB\")").ToList();

Now, Do I need to loop through this object to pull out the properties so that I can use them such as this?

foreach (var prop in CheckInVars.GetType().GetProperties())
        {

            Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(CheckInVars, null));
        }

Or can I directly work off of that IEnumberable<CheckInVar> Object, or do I need to convert that to work with it?

public class CheckInVar
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Column("ID")]
    public int ID { get; set; }
    public string Code { get; set; }
    public string VarValue { get; set; }
    public string AccessMethod { get; set; }
    public string Active { get; set; }
    public string DateCreated { get; set; }
    public string DateUpdated { get; set; }
    public string UpdatedBy { get; set; }
}
1
0
11/16/2016 10:17:48 PM

Accepted Answer

Yes.

If you, for some reason, wish to access each collection (IEnumerable) item's properties via reflection, then you will have to loop through the IEnumerable and process each item in turn.

Using your example:

foreach(var checkInVar in CheckInVars)
{
    foreach(var prop in checkInVar.GetType().GetProperties())
    { 
        Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(checkInVar)); 
    }
}

As others have mentioned though, is reflection really necessary? Can you not access the properties directly?

I'm guessing you may be using reflection to allow changes to the CheckInVar type without having to change your processing code.

1
11/16/2016 11:10:23 PM

Popular Answer

Try using foreach:

IEnumerable<CheckInVar> CheckInVars = context.Database.SqlQuery<CheckInVar>(
    "Call getCheckinVars(\"WEB\")").ToList();

foreach(CheckInVar item in CheckInVars)
{
    Console.WriteLine("ID: " + item.ID.ToString());
    Console.WriteLine("Code: " + item.Code);
    Console.WriteLine("VarValue: " + item.VarValue);
    //....
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow