-1

I have an IList that holds an object that has fields name, Id, location, store, person, and amount. I don't want to have to retrieve the values for all of these fields by writing a statement for each property

ex.

IList<CutDetail> btiCollection;
btiCollection[0].Id
btiCollection[0].location

Is there anyway that I can iterate through this list and retrieve the data within their fields without having to specifically name what they are? Any assistance would be appreciated.

woof
  • 83
  • 2
  • 8
bluesky
  • 624
  • 2
  • 14
  • 25

2 Answers2

2

If you want to retrieve the value of all properties of the item you can use Reflection to create a list of functions that retrieves the property values:

List<Person> people = new List<Person>();
people.Add(new Person() {Id = 3, Location = "XYZ"});

var properties = (from prop in typeof (Person).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                    let parameter = Expression.Parameter(typeof (Person), "obj")
                    let property = Expression.Property(parameter, prop) 
                    let lambda = Expression.Lambda<Func<Person, object>>(Expression.Convert(property, typeof(object)), parameter).Compile()
                    select
                    new
                        {
                            Getter = lambda,
                            Name = prop.Name
                        }).ToArray();


foreach (var person in people)
{
    foreach (var property in properties)
    {
        string name = property.Name;
        object value = property.Getter(person);
        //do something with property name / property value combination.

    }
}

The property value can also be retrieved using reflection, but this is considerably slower and might become noticable if you have a very long list/many properties.

Bas
  • 26,772
  • 8
  • 53
  • 86
-3

use List<CutDetail>instead of IList<CutDetail>

Manish Sharma
  • 2,406
  • 2
  • 16
  • 31