Pergunta

I have a class contains 4 properties:

class MyClass
{
    public int i{get;set;}
    public double d{get;set;}
    public string s{get;set;}
    public char c{get;set;}
}

And a list of this class:

var lstSource = new List<MyClass>
{
    new MyClass {i = 1, d = 1.2, s = "s1", c = '1'},
    new MyClass {i = 2, d = 2.2, s = "s2", c = '2'},
    new MyClass {i = 3, d = 3.2, s = "s3", c = '3'}
};

Now I want to get name of some of these properties from end-user and gets him a list of type anonymous contains wanted properties. User gives us list of wanted properties as a collection of string (name of wanted properties). For example assume list of wanted properties is like this:

var wantedProperties = new List<string> {"i", "s"};
  • Problem1: How to get only these properties from lstSource?

  • Problem2: How to provide type of every property as new variable in anonymous list? For every item in "wantedProperties" it most add another variable to resulted list hat shows type of wanted property. At this example resulted list most be like this:

    {
        {WantedProperty1_Value = 1,WantedProperty1_Type = typeof(int)},
        {WantedProperty2_Value = 2,WantedProperty2_Type = typeof(string)}
    }
    
Foi útil?

Solução

First off, your MyClass has fields, not properties. You'll have to change those to public int i {get; set;}, for example.

Now, you can use reflection to get the value and type of a property identified by its name.

foreach(MyClass obj in lstSource)
{
    foreach(string propertyName in wantedProperties)
    {
        PropertyInfo property = typeof(MyClass).GetProperty(propertyName);

        object value = property.GetValue(obj);
        Type propertyType = property.PropertyType;
    }
}

If the property is not public, you'll have to use a different overload of GetProperty and use the BindingFlags.NonPublic | BindingFlags.Instance binding flags.

Now all you have to do is build the result set.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top