Home > database >  How to convert class properties of single type to list of that type
How to convert class properties of single type to list of that type

Time:05-04

Given the following class:

class MyClass {
    readonly MyType Object1 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
    readonly MyType Object2 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
    readonly MyType Object3 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
    readonly MyType Object4 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
    // etc, there are 100  in this class, all of the type MyType
}

Is there a way I can turn this into a list of either the type MyType or the prop Prop1?

The class only contains properties of the type MyType.

CodePudding user response:

To do this, we will use Reflection to get a list of all strings in the Prop1 properties of all fields in MyClass.

Given that you have some instance of MyClass, you can get the list of strings with a simple one-liner like this:

MyClass instance = new MyClass(); // This could of course be gotten from somewhere else.

List<string> prop1s = instance.GetType().GetRuntimeFields().Select(p => (MyType)p.GetValue(instance)).Select(p => p.Prop1).ToList();

If you suddenly want to get some other property inside of MyType, you can simply change which property you select in the last Select().

Here we use reflection to get all fields (.GetRunTimeFields()) inside of the type MyClass, and since we know that all fields are of type MyType we can just cast all of the fields to MyType and then simply select the Prop1 property. Finally we just do ToList() to have it as a list, you could of course use it as an IEnumerable<string> or an array, but hopefully this should show you how you get the property you wanted as as list.

If you instead just want to have a list of MyType, then you could skip the last Select() like this:

List<MyType> myTypes = instance.GetType().GetRuntimeFields().Select(p => (MyType)p.GetValue(instance)).ToList();
  • Related