dimanche 16 octobre 2022

given a DI Generic object of

yes, while there are other answers for Compile time, but not runtime; i.e. I can do this at compile time when I have the object name; However after searching SO I was unable find an answer on SO for RUNtime, when using a generic object at runtime.

Question:

Given an DI injected someObjectList at RUNtime, of a Generic POCO/ViewModel object of <T>; for e.g. myCustomerList or myZooAnimals whatever the service injects,

How can get back a List<AttributeName, List<DistinctValues>> of ALL the distinct values for EACH col/prop or attribute of that object??

For e.g. you have two different objects

// For e.g. this are the objects or data
Customer[Name, Address, Phone ...]

Zoo[Animals, Country, IsAmphibian ...]

Objective/ get back all the distinct values by property:

 //List<AttributeName, List<DistinctValues>>
  public List<string, List<string>> GetDistinctValuesByProperty<T>(List<T> injectedList) {
  ...
  return List<AttributeName, List<DistinctValues>>
  }

At runtime, how can I pass in an object<T>(CustomerList) and get distinct values for EACH attribute DistinctNames, DistinctAddress & DistinctPhone


What I tried:

// Option 1: 
this only works at ** compile time and requires that i know the properties of the instance ahead of time, 
// ** How do I make this this generic to work for any object and all properties at runtime

   var distinctAddress= myCustomerList.Select(x => x.Address).Distinct();


// Option 2:
// I tried reflection, to get the property names at ** runtime, 
// but I could not figure out ** how to get the distinct properties and values for each

    foreach (var objectPropertyName in typeof(myObject).GetPropertyNames())
        {
            distinctAttirbutesList.Add(myObject.Select(m => m.objectPropertyName).distinct;
          ... no clue stuck.. tried to add the property name from reflection

        }





Aucun commentaire:

Enregistrer un commentaire