none
How to Iterate in Ienumerable (dynamic) RRS feed

  • Question

  • Hi,

    I have a List of IEnumerable values which i would like to iterate and get each and every values.I will not be able to explicitly say the values in the iteration.

    var lst  = list of IEnumerable 

      foreach (dynamic item in lst)
    {
     // iterate all the fields inside this, cant mention the field name explicitly.

    // Don't want to access field lik this  (eg. var data = item.fieldname1)

    }


    Thursday, November 8, 2018 5:55 AM

All replies

  • Hi,

    I have a List of IEnumerable values which i would like to iterate and get each and every values.I will not be able to explicitly say the values in the iteration.

    var lst  = list of IEnumerable 

      foreach (dynamic item in lst)
    {
     // iterate all the fields inside this, cant mention the field name explicitly.

    // Don't want to access field lik this  (eg. var data = item.fieldname1)

    }


    https://social.msdn.microsoft.com/Forums/en-US/3894982b-9670-4e24-8748-0e4e339a038a/ef-dynamic-type-the-sqlparameter-is-already-contained-by-another-sqlparametercollection?forum=adodotnetentityframework

    I gave you the answer in the link above, which is to use late binding. You are not coming around it in using an object that has been defined using dynamic, becuase dynamic is the equivalent of using Object that is the base definition object for all objects used in .NET.

    Thursday, November 8, 2018 6:22 AM
  • Try this example:

    public class MyClass

    {

        public int field1;

        public int prop1 { get; set; }

    }

     

    . . .

    var data = new List<MyClass>();

    data.Add( new MyClass { field1 = 100, prop1 = 200 } );

    data.Add( new MyClass { field1 = 300, prop1 = 400 } );

    IEnumerable lst = data;

    foreach( dynamic item in lst )

    {

        Type type = item.GetType();

        var fields = type.GetFields();

        foreach( FieldInfo field in fields )

        {

            var name = field.Name;

            var value = field.GetValue( item );

            Console.WriteLine( "Field Name = {0}, Value = {1}", name, value );

        }

        var properties = type.GetProperties();

        foreach( PropertyInfo property in properties )

        {

            var name = property.Name;

            var value = property.GetValue( item, null );

            Console.WriteLine( "Property Name = {0}, Value = {1}", name, value );

        }

    }

     

     

    If required, make sure that Microsoft.CSharp is referenced, and the .NET Framework is 4.5 or above.



    Thursday, November 8, 2018 6:40 AM