mercredi 17 février 2021

Trying to use reflection to concatenate lists of objects

I have below class

public class HydronicEquipment
{
    public List<LibraryHydronicEquipment> Source { get; set; }
    public List<LibraryHydronicEquipment> Distribution { get; set; }
    public List<LibraryHydronicEquipment> Terminals { get; set; }
}

and then i have the below class for "libraryHydronicEquipment"

public class LibraryHydronicEquipment : IEquipmentRedundancy
{
    public string Name { get; set; }
    public RedundancyStatus RedundancyStatus { get; set; }
    public EquipmentRedundancy EquipmentRedundancy { get; set; }
 }

I am trying to concatenate the list of "LibraryHydronicEquipment" objects available from all three properties (i.e) from source, distribution and terminal and General concatenate method will looks like as this below

 var source = hydronicEquipment.Source;
 var distribution = hydronicEquipment.Distribution;
 var teriminals = hydronicEquipment.Terminals;
 Source.Concat(Distribution).Concat(Terminals)

I am trying to achieve the same using reflection and the code looks like as below

 foreach (var (systemName, hydronicEquipment) in hydronicSystemEquipment)
 {
     bool isFirstSystem = true;                   
     var equipmentList = new List<string> { "Source", "Distribution", "Terminals" };
     var redundancyequipmentList = GetRedundancyEquipment(hydronicEquipment, equipmentList);                                  
  }

and the method GetRedundancyEquipment is looks like below

private static IEnumerable<IEquipmentRedundancy> GetRedundancyEquipment(HydronicEquipment hydronicEquipment, List<string> equipmentList)
{
    IEnumerable<IEquipmentRedundancy> equipmentRedundancies = new List<IEquipmentRedundancy>();
    dynamic equipmentResults = null;
    foreach(var equipment in equipmentList)
    {
        var componentList = hydronicEquipment.GetType().GetProperty(equipment).GetValue(hydronicEquipment, null) as IEnumerable<IEquipmentRedundancy>;
       equipmentResults =  equipmentRedundancies.Concat(componentList);
    }
    return equipmentResults;
}

The problem here is even though i have Source is having list of objects and Distribution is having list of objects, the equipmentResults is giving only one object instead of list of concatenated objects.

I am trying to return the IEnumerable<IEquipmentRedundancy> at the end using reflection method but it seems not working with the above code.

Could any one please let me know how can i achieve this, Many thanks in advance.





Aucun commentaire:

Enregistrer un commentaire