LittleTin LittleTin - 20 days ago 5
C# Question

How to use foreach in custom element

I have a custom element like this

public class Unit{
public int ID { get; set; }
public string name { get; set; }
...
}


I want to use foreach get the element like this

Unit = new unit;
foreach(var data in unit){
Console.WriteLine(data);
}


It will equals like this

Unit = new unit;
Console.WriteLine(unit.ID);
Console.WriteLine(unit.name);
...

Answer
void Main()
{
    Unit unit = new Unit();
    foreach (var property in typeof(Unit).GetProperties())
    {
        Console.WriteLine(property.GetValue(unit));
    }
}

public class Unit
{
    public int ID { get; set; }
    public string name { get; set; }
 //   ...
}